I'm new with ArrayList. I don't get it.
If I use int[] as the ArrayList item there is an error saying:
The method put(int) is undefined for the type ArrayList<int[]>.
If I use int the error says:
Syntax error on token "int", Dimensions expected after this token
I tried to use add() still the same...
You can't use primitive types int etc, as the "type" of an ArrayList. You must use the wrapper class Integer instead. Also, I stand to be corrected, but I don't think you can have an ArrayList of an array type for similar reasons. Perhaps ArrayList<ArrayList<Integer>> would work, as slightly ugly as that is?
EDIT: And while my Android experience is somewhat minimal and rusty, ρяσѕρєя K's comment about R.layout.foo always returning an int is certainly right.
Use something like this :
ArrayList<Integer []> mArrayList = new ArrayList<Integer[]>();
Integer [] layouts = {R.layout.layout1,R.layout.layout12,...};
mArrayList.add(layouts);
ArrayList<Integer> mArrayList = new ArrayList<Integer>();
mArrayList.add(R.layout.layout1);
mArrayList.add(R.layout.layout2);
...
Related
I have an array like
int [] nums={1,2,3,1,1,3};
So i wanted it convert it into an vector
I did try
Vector<Integer> num= new Vector<Integer>(Arrays.asList(nums));
and got this error
java: method addAll in class java.util.Collections cannot be applied to given types;
required: java.util.Collection<? super T>,T[]
found: java.util.Vector<java.lang.Integer>,int[]
reason: inference variable T has incompatible bounds
Is there a way to change the types or a faster method than this?
NB: Before I answer the question, Vector is deprecated and should never be used. You're looking for List. Whatever property Vector has that makes you think you need it, I really doubt it.
The problem here is that List (and Vector) are generified, and generics cannot be a primitive type. So, int[] and Integer[] aren't the same thing, and for the same reason, you can't casually turn an int[] into a List<Integer>. Instead, Arrays.asList(someIntArray) gives you a list with only one element in it, and that list is of type List<int[]> - in other words, nums is treated as the single element of a list of int arrays.
There is no method in the java.* libraries that turns an int[] into a List<Integer> (or Vector<Integer>, naturally).
An easy-ish way to do it:
List<Integer> list = Arrays.stream(nums).mapToObj(x -> x).toList();
This will first create an IntStream of your numbers. It then maps the int values to Integer values, using the identity operation which gets automatically sugared into x -> Integer.valueOf(x) (if you find it more readable like so, then go ahead and write it like that), and then turns the whole thing into a list. If toList() doesn't work - you're on java pre-16, write .collect(Collectors.toList()) instead of .toList().
If you don't like the above, a simple for loop would then do the job. This works just as well:
List<Integer> list = new ArrayList<Integer>();
for (int n : nums) list.add(n);
I am trying to implement bucket sort and I want to create an arraylist for each index of an array. I want to do something like this:
int bucket[]=new int[max+1];
for(i=0;i<=max/5;i++)
{
bucket[i]=new ArrayList<Integer>();
}
But the above code doesn't work and throws an error. It states "generic array creation".I know that generic array types are not allowed in java but I can't understand where generic types comes here I mean something like or .I also want to know is there a way to cast Integer to int while creating the ArrayList I hope doing so will fix this.
Your data types do not match...
You are trying to put an ArrayList<Integer> into a int[]. It cannot hold this type of data!
please reconsider what you want to have:
int[][]
ArrayList<int[]>
ArrayList<ArrayList<Integer>>
ArrayList<Integer>[] <--- thi is not well-supported due to the way generics work
If you want higher performance, you should have a look at GNU Trove, and maybe use
ArrayList<TIntList>
which should use much less memory than ArrayList<ArrayList<Integer>>.
If your data size is fixed, you probably are looking for
int[][] bucket = new int[max+1][max/5+1];
I just start to learn Java and I am getting "#SuppressWarnings("unchecked")"
I am sure that one of my static variable is making trouble
static ArrayList<Integer>[] docNumber = (ArrayList<Integer>[]) new ArrayList[20];
eclipse said "Type safety: Unchecked cast from ArrayList[] to ArrayList[]"
but i am not really sure how to avoid this problem
can you tell me how to fix this problem?
thanks
Can't be avoided with arrays.
Use a List<List<Integer>> instead.
In order to avoid the #SuppressWarnings(“unchecked”) you should give the compiler the information needed to perform all type checks that would be necessary to ensure type safety, see unchecked FAQ.
In your case, I assume that you are trying to maintain a list of document integers, for this you will need:
List<Integer> docNumber=new ArrayList<Integer>();
If you would like to keep a list of lists then you can do:
List<List<Integer>> docNumber=new ArrayList<List<Integer>>();
Are you trying to achieve this (List of Array Of Integer)?
static ArrayList<Integer[]> docNumber = new ArrayList<Integer[]>();
Ok basically what I am doing is i have a jtable in which users can enter their information into the table, I then want to be able to save it into a text file. The problem I am running into however is along the lines of this.
private static String dataValues[][];
I want to be able to declare dataValues like this so I can accesses it in every method so I can add rows to my jtable like this:
dataValues = {{number, owner, txtDate"}};
tableModel.addRow(dataValues);
however I get an error on the dataValues saying that "Array constants can only be used in initializers." And i dont really understand what that means.
if I declare the variable like this in the actual method it works.
String[][] dataValues = {{number, owner, txtDate}};
But I need to be able to access it anywhere in the program so declaring it like that will not help me.
Thanks for the help in advance.
The JTable represents the data internally with a TableModel. What the JTable does in the constructor is convert the initial array into the TableModel. What you need to do is think in terms of TableModels as described in the following link: http://docs.oracle.com/javase/tutorial/uiswing/components/table.html#data
You can always initialize array variables like so:
static String[] row;
and later:
row = new String[]{"foo", "bar", "baz"};
"Array constants can only be used in initializers." - is a java syntax error.
You can not use statement like :
int[] a = new int [3];
a = {1,2,3};
I think with "a = {...}" it is not clear to the "javac" compiler what the type of "a" is.
Especially when dealing with array of objects such as Strings.
So use of constants allowed are
int[] a = {1,2,3};
Or possibly
a = new int [] {1,2,3};
Above should the only way if you really want to do what you are trying to do.
Essentially, this is how your code would look like:
dataValues = new String[][] {{"number", "owner", "txtDate"}};
That for the Java syntax error part. For JTable stuff, please follow #Stphane G's answer
Have a look at this answer i had given for a question on using a generic table model. You will find using a class with the fields representing the columns of the table a very easy implementation to work with
Is there a generic TableModel we can use in JTables?
I've found plenty of entries here that say
someFunc(new int[]{1,2,3});
works for calling methods and being used in a for/each loop.
//======
How about for assignment into a collection?
I've tried this:
ArrayList<int[]> data = new ArrayList<int[]>();
data.add(new int[]{21, 19629});
and I get "identifier expected" and "illegal start of type".
Is there any thing I can do to make this work?
You've made a list of arrays. Was that really what you intended, or did you mean to ask about something like
ArrayList<Integer> data = new ArrayList<Integer>();
data.add(new int[]{1,2,3});
?
In any case, familiarize yourself with the Arrays and Collections classes--they contain a lot of utilities that come in handy in cases like this.
Easiest way to make a list from an array:
List<String> myList = Arrays.asList("Hello", "There", "Foo", "Bar);
Note the list is fixed size and backed by the input array so changes to the list actually write to the array. Adding or removing elements will likely result in an UnsupportedOperationException. If you intend to mess around with the array such as adding or removing elements you may need to copy the elements into another list
Check out guava, especially the google collections part.
Several of the collection classes define a static method of(...) which will the add all objects given to that collection.
Combined with static imports this allows very concise colleciton intializations on-the-fly.
e.g.
import static com.google.common.collect.ImmutableList.of;
...
someFunc(of("abc","def","ghi"));
will call someFunc with a list of strings.
In fact, this code works if you want to make a list of table of integers.
public static void main(String[] args) {
List<int[]> data = new ArrayList<int[]>();
data.add(new int[]{21, 19629})
for(int[] tab : data){//I loop each tab (only one here)
for(int i: tab){//I loop each values
System.out.println(i);
}
}
}
print
21
19629
This may be a limitation of the language syntax, or a bug in the spec that the identifier production is being found before the expression production in the parsing of the method call syntax. Don't mix anonymous array declaration inside the method call.
data.add(new int[]{21, 19629});
and I get "identifier expected" and
"illegal start of type".
The "identifier expected" in data.add(...) is probably caused by the compiler expecting an identifier and finding an expression that resolves to an anonymous instance. There are several places where that very syntax is acceptable, I'm not sure why data.add() needs an identifier.
The "illegal start of type" may be that the compiler thinks the expression is an anonymous type declaration but the syntax doesn't allow for that in a method call.
Try creating it using a variable, then pass the variable as the method arg.
int[] nums = new int[] {0,1,2};
data.add(nums);
In looking for more specifics of the ArrayList.add() grammar, I found this answer on a similar problem someone had learning ArrayList. JavaGlossary has a good set of Compile-time errors.