I currently have a project that requires the use of abstraction and generics, but I don't even know where I should start for this. The abstract class is as follows.
public abstract class Links<AType> {
abstract AType getElem(); //returns the head of the list
abstract Links<AType> getNext(); //return the next link
}
This is the class that extends the abstract class
public class Cons<AType> extends Links<AType> {
AType elem;
Links<AType> next;
Cons(AType elem, Links<AType> next) {
this.elem = elem;
this.next = next;
}
@Override
AType getElem() {
return elem;
}
@Override
Links<AType> getNext() {
return next;
}
}
Here's another class that extends the abstract class
public class Nil<AType> extends Links<AType> {
Nil(){}
@Override
AType getElem() {
return null;
}
@Override
Links<AType> getNext() {
return null;
}
}
And here is the class that is supposed to implement everything
public class LList<AType> {
Links<AType> list;
LList() {
list = new Cons<>();
}
Links<AType> getList() {
return list;
}
AType get(int n, AType a) {
Cons<AType> aTypeCons = new Cons<>(a, list);
return null;
}
void add(AType elem) {
//add to head of list
}
void remove(int i) {
//remove ith element
//do nothing if i is invalid
}
void print() {
//prints the list
}
}
I just need some help figuring out where to actually start in making the LList class. I can't figure out the constructor because Links is abstract, so I can't make that an object, and I can't make a new Cons<> because there are no elements that are passed into the constructor. However, the constructor is supposed to instantiate a new list. I also can't figure out how I'm supposed to be able to access an individual element of that list. If I can just have a bit of understanding of what needs to happen in the constructor, I should be able to figure out how to implement the rest of the methods.
Your LList
is a singly-linked list, where each element has a value and a link to the list that follows. The final element of the list will always be a Nil
object, which represents an empty list. When you first initialize an empty list, you can just assign list = new Nil<>();
. When you add an element to the list, you can reassign it as list = new Cons<>(elem, list);
.
To access an an element in the list by index, just use a while
loop that calls getNext()
until it's either reached the desired index or found the end of the list.
AType get(int n) {
Links<AType> current = list;
while (n > 0 && current instanceof Cons) {
current = current.getNext();
n--;
}
return current.getElem();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.