0

First of all i have little experience in Java.

Getting to my question, I am implementing my own list with my own methods.

public class MyList<E> implements List<E>{
.....

One of this methods returns the size of my list

 public int getSize(){
 ....
 }

Then I have two other methods that would be more simple if I could somehow apply this method to my list. How so?

I have a method that has to compare if a given list is equal to this list

 public boolean equals(Lista<E> list){
 ....
 }

I had though about first comparing the size of both list, and if they don't match it returns false. if they do, it continues to compare each element. Is this possible? How would I applied getSize ? If this is not possible, i will just compare element by element.

My other method has to return an array of each element

public Object[] toArray() {
   E myarray = new E[??]

As you can see, i dont' know how to declare this array. I would have to know beforehand the size of my list. I though about passing as an argument (which would solve the problem) but i need to solve it this way.

3 Answers 3

1

You call list.getSize(), like so:

if (list.getSize() != this.getSize()) {
    return false;
}
Sign up to request clarification or add additional context in comments.

Comments

1

Since you cannot create generic array in Java, you would have to do

public Object[] toArray() { 
   E[] myarray = (E[]) new Object[this.getSize()];

Comments

0

Simply use the getSize() method:

E myarray = new E[getSize()];

1 Comment

new E[...] does not compile. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.