java errors in dr java

2019-09-21 13:49发布

问题:

I added import java.util.ArrayList; (per suggestions here) to my code and then I got 2 different kinds of errors. They are:

error: the type of the expression must be an array type but it resolved to java.util.ArrayList<java.lang.Integer>

and:

error: length cannot be resolved or is not a field.

Can anyone tell me what they mean? I've tried changing the length statements by adding () at the end but that cause more errors then I started with.

回答1:

For an ArrayList you need to call the .size() Method to get the number of elements, not length. You can't just treat the ArrayList like a basic array. Please provide some code samples for help with the other error.

int i = myList.size();

EDIT:

I've just seen, that someone actually mentioned that already in another question of yours. How to modify a java program from arrays to arraylist objects?

Since you try to employ a method of community-coding just some tips for you to grow and the community to save some nerves ;)

Try to keep the JavaDoc open in a browser while you code: http://download.oracle.com/javase/6/docs/api/

If you want to experiment with an ArrayList, look up which methods and properties it has. Usually, it also links to proper tutorials like, e.g. how to use collection classes. It's probably quicker to browse the JavaDoc rather than posting a question here and it will give you a good general picture of basic Java classes.



回答2:

For your second error, it seems like you are trying to use arrays and Lists interchangeably, although they are two separate data types.

In your code, you probably have something like:

int[] myArray = new ArrayList<Integer>();

You need to figure out which type you want to use. If you need an array, use:

int[] myArray = new int[0]; // replacing 0 with your initial array size

If you need a list, use:

List<Integer> myList = new ArrayList<Integer>();

As you've mentioned before, you're new to Java. You might find value in reading through some of the basic tutorials; they may give you a better understanding of what's happening with your code.