Jag behöver hjälp med java LinkedList implements Stack.

Permalänk
Medlem

Jag behöver hjälp med java LinkedList implements Stack.

Jag försöker lösa en lab men har fastnat nu en hel dag på det här. Jag förstår inte varför jag få fel meddelande
"class 'LinkedList' must be either declared abstract or implement abstract method 'push(T)' in Stack"
kan någon hjälpa mig?
PS jag har också problem med min @Override, den säger att den inte "overrida" min push metod, antar att om första problem löses så kanske den andra funkar också, eller?

public interface Stack { void push(T o); T pop(); T top(); int size(); boolean isEmpty(); } /** * A singly linked list. * */ import java.util.*; import org.junit.Before; import org.junit.Test; import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.*; public class LinkedList<T> implements Stack { private ListElement<T> first; // Points to the first element on the list. private ListElement<T> last; // Points to the last element on the list. private int size; // Number of elements in list. /** * A list element. */ private static class ListElement<T> { public T data; public ListElement<T> next; public ListElement(T data) { this.data = data; this.next = null; } } /** * Creates an empty list. */ public LinkedList() { // TODO "Done" first = last = null; size = 0; } public static void main(String[] args){ } /** * Inserts the given element at the beginning of this list. * * @param element An element to insert into the list. */ public void addFirst(T element) { // TODO "Done" first = last= new ListElement<T>(element); last.next = null; } /** * Inserts the given element at the end of this list. * * @param element An element to insert into the list. */ public void addLast(T element) { // TODO "Done" if( first == null) { addFirst(element); } else { ListElement<T> temp = last; last = new ListElement<T>(element); temp.next = last; last.next = null; } } /** * @return The head of the list. * @throws NoSuchElementException if the list is empty. */ public T getFirst() { // TODO "Done" if(first == null) throw new NoSuchElementException(); return first.data; } /** * @return The tail of the list. * @throws NoSuchElementException if the list is empty. */ public T getLast() { // TODO "Done" if(last == null) throw new NoSuchElementException(); return last.data; } /** * Returns an element from a specified index. * * @param index A list index. * @return The element at the specified index. * @throws IndexOutOfBoundsException if the index is out of bounds. */ public T get(int index) { // TODO "Done" if (index < 0 || index >= size()) throw new IndexOutOfBoundsException(); ListElement<T> temp = first; for (int i = 0; i < index; i++) temp = temp.next; return temp.data; } /** * Removes the first element from the list. * * @return The removed element. * @throws NoSuchElementException if the list is empty. */ public T removeFirst() { // TODO "Done" if(first == null) throw new NoSuchElementException(); else if (first.next == null) { first =last= null; return null; } else { ListElement<T> temp = first; first = first.next; return temp.data; } } /** * Removes all of the elements from the list. */ public void clear() { // TODO "Done" first = last = null; } // Adds the element to the top of the stack. @Override public void push(T o) { addLast(o); } /**Removes and returns the top element in the stack, that is the element * that was last added to the stack. Throws an EmptyStackException * (you need to import this, see the docs!) if the stack is empty! * @return */ @Override public T pop() { T temp = last.data; for(int i = 1; i < size;i ++){ last = first.next; } size --; return temp; } /** Returns the top element in the stack without removing it. Throws an EmptyStackException (you need to * import this, see the docs!) if the stack is empty! * @return */ @Override public T top() { if (first == null); throw new EmptyStackException(); else{ return last.data; } } /** * @return The number of elements in the list. */ public int size() { // TODO "Done" if( first == null) size = 0; else{ size++; ListElement<T> temp = first; while(temp.next != null) { temp = temp.next; size ++; } } return size; } /** * Note that by definition, the list is empty if both first and last * are null, regardless of what value the size field holds (it should * be 0, otherwise something is wrong). * * @return <code>true</code> if this list contains no elements. */ public boolean isEmpty() { return first == null && last == null; } /** * Creates a string representation of this list. The string * representation consists of a list of the elements enclosed in * square brackets ("[]"). Adjacent elements are separated by the * characters ", " (comma and space). Elements are converted to * strings by the method toString() inherited from Object. * * Examples: * "[1, 4, 2, 3, 44]" * "[]" * * @return A string representing the list. */ public String toString() { // TODO String list = ""; ListElement<T> current = first; while(current.next != null){ list += current.next + ","; } return list; } }

Permalänk
Medlem

Om du kikar på metodsignaturen push() för klassen Stack i Java-dokumentationen (https://docs.oracle.com/javase/8/docs/api/java/util/Stack.htm...) borde det vara uppenbart varför din push metod inte overridear den (jämför return-typerna).

Visa signatur

Citera för svar!

Stationär: Fractal Design Define R6 | Asus Z370-P | Intel i7 8700k @ 3.7 Ghz | Corsair Vengeance LPX 32GB CL15 @ 3000 Mhz | Asus STRIX GTX960 4GB | Fractal Design Celsius S24 | 5 TB HDD | 250GB SSD (Samsung 850 EVO), 128GB SSD (Crucial M4) | Corsair HX 850W | W10
Bärbar: Sony Vaio Pro 13.3" | i7-4500U | 8GB RAM | 256GB SSD | Ubuntu

Permalänk
Medlem

@RedRetro:
Menar du att den måste returnera något? Min uppgift säger att den ska vara void.

"
Task 1 - Create a Stack Interface
A stack is an abstract data type (in Java "collection") that usually supports at least the 5 methods outlined below.

void push(T) Adds the element to the top of the stack.

T pop() Removes and returns the top element in the stack, that is the element that was last added to the stack. Throws an EmptyStackException (you need to import this, see the docs!) if the stack is empty!

T top() Returns the top element in the stack without removing it. Throws an EmptyStackException (you need to import this, see the docs!) if the stack is empty!

int size() Returns the number of elements in the stack.

boolean isEmpty() indicates whether the stack is empty. "

Permalänk
Medlem
Skrivet av RedRetro:

Om du kikar på metodsignaturen push() för klassen Stack i Java-dokumentationen (https://docs.oracle.com/javase/8/docs/api/java/util/Stack.htm...) borde det vara uppenbart varför din push metod inte overridear den (jämför return-typerna).

Nu är mina Java-kunskaper lite rostiga, men TS implementerar väl sitt eget interface 'Stack', och inte 'Stack'-klassen (nyckelordet implements vs extends)?

@Hannynha: Rent spontant känns det som att du saknar typ-parametern T i Stack. Prova:

public interface Stack<T>

och

public class LinkedList<T> implements Stack<T>

Visa signatur

Intel Core i5 8600k @ 4.7 GHz - Gigabyte Aorus GTX 1080 TI - Asus PRIME Z370-A
- Corsair Vengeance LP 16 GB - EVGA Supernova G2 850W - NZXT H500i

Permalänk
Medlem

Behöver man verkligen köra @Override när man implementerar ett interface? Det är väl något man gör när man arbetar med klassarv ?

Permalänk

Kanske krockar din LinkedList med javas inbyggda java.util.LinkedList, som du råkar importera med din import av java.util.*.

Visa signatur

Dator: i5-13600K, Asus Prime Z690-P, Noctua NH-D14, Kingston Fury Beast RGB 32GB DDR5-6000, Gigabyte RTX 4090 gaming OC, Seasonic Platinum SS-1000XP, Lian-Li Lancool 215, Samsung 980Pro 2TB M.2 NVME, Acer Predator XB323QKNV 4k 144Hz

Permalänk
Medlem

@Fille625: har provat. Det hjälpte inte. säger fortfarande samma sak. :'(

Permalänk
Medlem

@Milky Way: Jag tror inte. Den borde inte blir ett problem.

Permalänk
Medlem
Skrivet av Hannynha:

@Fille625: har provat. Det hjälpte inte. säger fortfarande samma sak. :'(

Vilken Java-version kör du? Testade precis, och följande fungerar som tänkt med JDK8:

/** * A singly linked list. * */ import java.util.*; import org.junit.Before; import org.junit.Test; import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.*; public class LinkedList<T> implements Stack<T> { private ListElement<T> first; // Points to the first element on the list. private ListElement<T> last; // Points to the last element on the list. private int size; // Number of elements in list. /** * A list element. */ private static class ListElement<T> { public T data; public ListElement<T> next; public ListElement(T data) { this.data = data; this.next = null; } } /** * Creates an empty list. */ public LinkedList() { // TODO "Done" first = last = null; size = 0; } public static void main(String[] args){ } /** * Inserts the given element at the beginning of this list. * * @param element An element to insert into the list. */ public void addFirst(T element) { // TODO "Done" first = last= new ListElement<T>(element); last.next = null; } /** * Inserts the given element at the end of this list. * * @param element An element to insert into the list. */ public void addLast(T element) { // TODO "Done" if( first == null) { addFirst(element); } else { ListElement<T> temp = last; last = new ListElement<T>(element); temp.next = last; last.next = null; } } /** * @return The head of the list. * @throws NoSuchElementException if the list is empty. */ public T getFirst() { // TODO "Done" if(first == null) throw new NoSuchElementException(); return first.data; } /** * @return The tail of the list. * @throws NoSuchElementException if the list is empty. */ public T getLast() { // TODO "Done" if(last == null) throw new NoSuchElementException(); return last.data; } /** * Returns an element from a specified index. * * @param index A list index. * @return The element at the specified index. * @throws IndexOutOfBoundsException if the index is out of bounds. */ public T get(int index) { // TODO "Done" if (index < 0 || index >= size()) throw new IndexOutOfBoundsException(); ListElement<T> temp = first; for (int i = 0; i < index; i++) temp = temp.next; return temp.data; } /** * Removes the first element from the list. * * @return The removed element. * @throws NoSuchElementException if the list is empty. */ public T removeFirst() { // TODO "Done" if(first == null) throw new NoSuchElementException(); else if (first.next == null) { first =last= null; return null; } else { ListElement<T> temp = first; first = first.next; return temp.data; } } /** * Removes all of the elements from the list. */ public void clear() { // TODO "Done" first = last = null; } // Adds the element to the top of the stack. @Override public void push(T o) { addLast(o); } /**Removes and returns the top element in the stack, that is the element * that was last added to the stack. Throws an EmptyStackException * (you need to import this, see the docs!) if the stack is empty! * @return */ @Override public T pop() { T temp = last.data; for(int i = 1; i < size;i ++){ last = first.next; } size --; return temp; } /** Returns the top element in the stack without removing it. Throws an EmptyStackException (you need to * import this, see the docs!) if the stack is empty! * @return */ @Override public T top() { if (first == null) { throw new EmptyStackException(); } else{ return last.data; } } /** * @return The number of elements in the list. */ public int size() { // TODO "Done" if( first == null) size = 0; else{ size++; ListElement<T> temp = first; while(temp.next != null) { temp = temp.next; size ++; } } return size; } /** * Note that by definition, the list is empty if both first and last * are null, regardless of what value the size field holds (it should * be 0, otherwise something is wrong). * * @return <code>true</code> if this list contains no elements. */ public boolean isEmpty() { return first == null && last == null; } /** * Creates a string representation of this list. The string * representation consists of a list of the elements enclosed in * square brackets ("[]"). Adjacent elements are separated by the * characters ", " (comma and space). Elements are converted to * strings by the method toString() inherited from Object. * * Examples: * "[1, 4, 2, 3, 44]" * "[]" * * @return A string representing the list. */ public String toString() { // TODO String list = ""; ListElement<T> current = first; while(current.next != null){ list += current.next + ","; } return list; } }

LinkedList.java

public interface Stack<T> { void push(T o); T pop(); T top(); int size(); boolean isEmpty(); }

Stack.java

public class Main { public static void main(String[] args) { // TODO Auto-generated method stub LinkedList<Integer> foo = new LinkedList<>(); foo.addFirst(5); System.out.println(foo.getFirst()); } }

Main.java
Visa signatur

Intel Core i5 8600k @ 4.7 GHz - Gigabyte Aorus GTX 1080 TI - Asus PRIME Z370-A
- Corsair Vengeance LP 16 GB - EVGA Supernova G2 850W - NZXT H500i

Permalänk
Medlem
Skrivet av Hannynha:

@Milky Way: Jag tror inte. Den borde inte blir ett problem.

Som @Fille625 mycket riktigt säger måste du parametrisera ditt interface. Just nu skriver du att push och pop hanterar en konkret typ "T", medan din implementation i LinkedList<T> är generisk.

Visa signatur

Kom-pa-TI-bilitet

Permalänk
Medlem

@Fille625: uppdaterade igår. få samma fel.

Permalänk
Medlem

@Teknocide: När jag ändra min push(T o) till push(<T> o) få jag iställe felet ("<>" röd under och meddelande parameter expected)
och ("o" röd och cannot resolve symbol o).

Permalänk
Medlem

Metodens signatur ska vara push(T o), inte push(<T> o).
Som de andra säger måste du paramatisera ditt interface. Alltså

public interface Stack<T>

Men som någon skrev tidigare så kam det nog bli konflikter med javas egna Stack-interface då du importerar det efter att du definerat ditt egna interface. Jag är osäker på hur det hanteras då. För att vara på den säkra sidan kan du testa byta namn på ditt interface till något annat. T.ex. MyStack<T> och implementera det istället.

public class LinkedList<T> implements MyStack<T>

Skickades från m.sweclockers.com

Permalänk
Medlem

Fixad nu, tror jag. Tack så mycket alla!