I've looked a lot through here and can't quite find why this line is wrong:
ArrayList <BigInteger> data = new ArrayList();
int [] primes = new int[25];
...
// Some initializing
...
data.get(i) = data.get(i).divide( BigInteger.valueOf( primes[place] ) ); //<----
...
// Rest of the code
Required: variable;
Found: value.. What I'm doing wrong?
First, you should fix your Raw Type (and I'd prefer the List interface) like
List<BigInteger> data = new ArrayList<>();
then you need to use set because you can't assign to the return value of a get like that.
data.set(i, data.get(i).divide(BigInteger.valueOf(primes[place])));
Also, it's worth noting that BigInteger(s) are (per the Javadoc) immutable arbitrary-precision integers.
= only works to assign variables, fields and array elements.
You probably want to call set.
data.set(i, data.get(i).divide(...etc...));
Related
If I can declare an Array of FloatLists: FloatList [][] values = new FloatList[3][3];
Why doesn’t it work to declare an Array of ArrayLists holding FloatLists like this: ArrayList<FloatList> [][] values = new ArrayList<FloatList>() [3][3];? OR EVEN: ArrayList<FloatList> [][] values = new ArrayList<FloatList> [3][3]();
How can this be achieved? Will it be hard to refer to the floats buried deep under its crusty texture?
Work from the inner-most type to the outer-most type. You start with FloatList:
FloatList
Then wrap that in an ArrayList:
ArrayList<FloatList>
Then you want an array of that:
ArrayList<FloatList>[]
Or a 2D array:
ArrayList<FloatList>[][]
That gives you the type for the declaration, but then you have to initialize the variable by giving it a value. Start with the array by giving it a size:
ArrayList<FloatList>[] array = new ArrayList[10];
This gives you an array of ArrayList<FloatList> objects, but they start out as null. To give them a value, you'd loop over every index in the array and use the new keyword to set the value of the index to an instance of ArrayList<FloatList>:
for(int i = 0; i < array.length; i++){
array[i] = new ArrayList<FloatList>();
}
For a 2D array, you'd use the same logic, just in a nested for loop.
Then to add a FloatList to an ArrayList at a specific index of the array, you'd do this:
array[i].add(new FloatList());
Finally, to add a float to a FloatList in an ArrayList at an index in the array, you'd do this:
array[x].get(y).append(0.5);
And to get a float out of an index in the FloatList in an ArrayList at an index in the array, you'd do this:
float f = array[x].get(y).get(z);
Putting it all together, it looks like this:
ArrayList<FloatList>[] array = new ArrayList[10];
for(int i = 0; i < array.length; i++){
array[i] = new ArrayList<FloatList>();
}
array[1].add(new FloatList());
array[1].get(0).append(0.25);
array[1].get(0).append(0.5);
array[1].get(0).append(0.75);
float f = array[1].get(0).get(2);
println(f);
ArrayList<FloatList> [][] values = new ArrayList[3][3];
Basically, you're declaring that you want an object that is a 3D array of ArrayLists, and not generating actual ArrayList objects.
Afterwards, you have to instantiate each of them, so for example:
values[0][0] = new ArrayList<>();
And so on.
It doesn't work because of the way the JVM provides Generics. Generics in Java is a front-end compiler feature that becomes raw type usages and casts at execution time.
What is the compiler doing when I use generics?
Here's a terribly-contrived example. Let's say I want to create a List<String> to store command line arguments that I will later use to kick off a new process with, like so:
List<String> cmd = new ArrayList<>();
cmd.add("java");
cmd.add("-jar");
cmd.add("path/to/my.jar");
...
String args = cmd.get(0)+" "+cmd.get(1)+" "+cmd.get(2);
At compile time, the compiler will check to make sure that I am using the String type every time I use a generic List method via cmd and throw an error if I try to use instances of an incompatible type. However, there's a little thing called erasure that happens during compilation, before execution. Effectively, under the hood, the compiler converts the code above into something like this:
List cmd = new ArrayList();
cmd.add("java");
cmd.add("-jar");
cmd.add("path/to/my.jar");
...
String args = (String)cmd.get(0)+" "+(String)cmd.get(1)+" "+(String)cmd.get(2);
So why doesn't my generic array code compile?
In your example, you wanted to create an array of a generic type, like so:
ArrayList<FloatList>[][] array = new ArrayList<FloatList>[n][m]; //Doesn't compile? What gives?
The problem is, because of type erasure, the ArrayList<FloatList> class type doesn't really exist, and now you've asked the JVM to create a 2-dimensional array of that non-existent type.
Okay, so what's the alternative?
Well ... it isn't pretty, but you could do something like this:
class ArrayListOfFloatList extends ArrayList<FloatList>{
...
}
//Somewhere else in your code:
ArrayListOfFloatList[][] myArray = new ArrayListOfFloatList[n][m];
//This will compile because ArrayListOfFloatList is a real class.
The only other way around this would be to not use arrays. Ugly, perhaps, but it's unfortunately a limitation of how Java is currently implemented.
I need to get three levels down into an array list. Here is my code on how I create the final product "rowList":
ArrayList<ArrayList> rowList = new ArrayList<ArrayList>();
ArrayList<ArrayList<String>> appList =new ArrayList<ArrayList<String>>();
ArrayList<String> arr = new ArrayList<String>();
int Id = -1;
int cc = rsmd.getColumnCount();
while(rs.next()){
if(Id == -1){
arr.add(rs.getString("name"));
Id= Integer.parseInt(rs.getString("Id"));
}
if(Id!= Integer.parseInt(rs.getString("Id"))){
Id= Integer.parseInt(rs.getString("Id"));
rowList.add(appList);
appList = new ArrayList<ArrayList<String>>();
arr.add(rs.getString("name"));
}
for(int i=2; i < rsmd.getColumnCount();i++){
arr.add(rs.getString(rsmd.getColumnName(i)));
}
appList.add(arr);
arr = new ArrayList<>();
}
rowList.add(appList);
So in the end rowlist will look something like this:
[0]
[0]
[0]Property 1
[1]Property 2
[2]Property 3
[1]
[0]Property 1
[1]Property 2
[2]Property 3
[1]
[0]
[0]Property 1
[1]Property 2
[2]Property 3
[1]
[0]Property 1
[1]Property 2
[2]Property 3
So my question would be how to get to the properties, the last level in the nested array? I can use rowList.get(0).get(0).toString() to return the string array, but rowList.get(0).get(0).get(0) doesn't work, and instead gives the error: cannot find symbol.
I would also like to be able to remove a property after I've retrieved it and set it to a string. That part can easily be worked around though, so it isn't vital.
This is because you're using a raw type:
ArrayList<ArrayList> rowList = new ArrayList<ArrayList>();
rowList.get(0) returns an ArrayList. Antoher .get(0) will return an Object, because you're using a raw type. And Object does not have a get method.
But Object does have a toString method, so you can call toString.
You simply have to change the declaration. This can be made easier using the diamond:
ArrayList<ArrayList<ArrayList<String>>> rowList = new ArrayList<>();
ArrayList<ArrayList<String>> appList = new ArrayList<>();
ArrayList<String> arr = new ArrayList<>();
Okay, let's think about the type of each result in the chained calls rowList.get(0).get(0).get(0). The easiest way to do this is to break each call into its own line so that we can figure out the type we need for the variable declaration. First of all, look at the declaration of rowList:
ArrayList<ArrayList> rowList = new ArrayList<ArrayList>();
This tells us that rowList.get(0) will return an ArrayList:
ArrayList arr = rowList.get(0);
Now rowList.get(0).get(0) is equivalent to arr.get(0). But this returns an Object:
Object obj = arr.get(0);
So rowList.get(0).get(0).get(0) is equivalent to obj.get(0). However, Object does not have a method named get(). This is why you get an error message.
In general, you should be very careful when chaining method calls. Typically this syntax is only used when a method returns a reference to the calling object. That way the return type is always the same and much easier to keep track of. When the return type differs on each successive method call, it can be difficult to keep track of.
The problem is that the ArrayList returned by rowList.get(0) is a raw type. So another get() call only returns an Object. You should use generics to specify the type of object in the "rows":
ArrayList<ArrayList<ArrayList<String>>> rowList = new ArrayList<>();
As you see here, generics can be used as the type inside of any <> just like you already did for the outermost level of ArrayList in your originaly code. (Note that in JDK 7+, you can use the diamond operator when creating an ArrayList. This greatly reduces duplicating the type information that already appears in the declaration.)
Better yet, you can declare your variables using the List interface in order to provide some flexibility in the concrete type used:
List<List<List<String>>> rowList = new ArrayList<>();
Is it possible to create a List of arrays(with fixed size) in Java?
I have tried these methods and they both give me a syntax error:
List<int[]> failedParameters = new ArrayList<int[3]>();
List<int[]> failedParameters = new ArrayList<new int[3]>();
What am I doing wrong?
No, you can't specify the array length as a Java type. However, you can wrap arrays in your own type. I'll let you decide if that is really practical (in case you have dozens of array lengths that you want to support):
class Int3 {
// Use final to indicate that the array length will remain unchanged
final int[] array = new int[3];
}
List<Int3> failedParameters = new ArrayList<Int3>();
Of course, if you go this far, why not just create an int-tuple of degree 3?
class Int3 {
int v1;
int v2;
int v3;
}
List<Int3> failedParameters = new ArrayList<Int3>();
You can use this method. It will not allow you to change the collection size (no add()/remove() operations).
List<> unmodiffableList = Collections.unmodifiableList(oListeRet);
Hi i am trying to add the values to list as show in below code. i am getting error.
for (String n2 : number ) {
List<String> ARRAY = new ArrayList<String>();
if (!ARRAY.contains(number)) {
ARRAY.add(number);
}}
But getting error while adding the number in to list.
error
java:271: error: no suitable method found for add(List<String>
ARRAY.add(number);
^
method List.add(int,String) is not applicable
(actual and formal argument lists differ in length)
method List.add(String) is not applicable
(actual argument List<String> cannot be converted to String by method invo
if i use like below
for (String n2 : number ) {
List<String> ARRAY = new ArrayList<String>();
if (!ARRAY.contains(n2)) {
Email(n2);
ARRAY.add(n2);
}
}
if i am using above. Though already email sent with value n2 again it is sending again.
For first it has to sent but for second time since it is already in array it should not sent right?
Problem with your code is you are adding number instead of n2
Change the code like this
List<String> ARRAY = new ArrayList<String>();
for (String n2 : number ) {
if (!ARRAY.contains(n2)) {
ARRAY.add(n2);
}
}
1) ARRAY should be outside of your for loop.
2) Replace if (!ARRAY.contains(number)) to if (!ARRAY.contains(n2 )).
Your code need to like this
List<String> ARRAY = new ArrayList<String>();
for (String n2 : number ) {
if (!ARRAY.contains(n2 )) {
ARRAY.add(n2);
}
}
You're trying to add a collection - numbers into a List of Strings.
I am assuming you are trying to add n2 into ARRAY.
ARRAY.add(n2);
I am afraid there is a bit more wrong with your code than just that one error. As has been pointed out many times, you are trying to add an iterable collection of strings, number to your Array rather than n2 which is the iteration variable. If you want to add complete Collection instances you can do so using addAll().
As for the rest, I strongly recommend sticking to the Java naming convention and using lower case names for your variables. This will improve readability as many members of the community stick with that convention. You can find a neat write-up here.
You also seem to, unless your code is highly simplified, make the mistake of declaring an ArrayList inside the scope of a loop. you are instantiating a new ArrayList every time you enter the loop. I am not sure that is what you want to do. Be sure to check your design.
Also, if you simply want to avoid having duplicate values, I would suggest using Set as it performs the check automatically using the hashCode() of each member on insertion to check for collisions. Try doing:
HashSet<String> uniqueSet = new HashSet<>(number);
You should now have a Collection of unique strings.
number is collection of string and you are adding int ARRAY instead add n2
List<String> ARRAY = new ArrayList<String>();
for (String n2 : number ) {
if (!ARRAY.contains(n2)) {
ARRAY.add(n2);
}
}
List<String> ARRAY = new ArrayList<String>();
for (String n2 : number ) {
if (!ARRAY.contains(n2)) {
ARRAY.add(n2);
}
}
List<String> ARRAY = new ArrayList<String>(); //have this out of the thread
I was wondering if it is possible to convert an Object into something else.
I have a Object which contains a series of numbers in a random order such as: 3, 4, 2, 5, 1 and wondering if I am able to turn it into an int[] or select certain elements from it, as in a number from the sequence?
EDIT:
so some of the code i have is:
//This contains all the different combinations of the numbers
ArrayList routePop4 = new ArrayList();
//This picks out the first one, just as a test
Object test = routePop4.get(0);
But the idea is that I want to loop through each element of test.
An Object cannot "contain a series of numbers". However many subclasses of Object, such as all of the Collections can "contain a series of numbers", and they come with a toArray() method to turn the contents of the collection into an array.
If you have a collection, but only have access to it as an Object, you need to cast it before you can work with it properly:
ArrayList<Integer> list = (ArrayList<Integer>)test;
Integer[] arr = list.toArray(new Integer[]{});
It's fairly rare in day-to-day Java to actually be working with variables cast as Object, if you are, it should be a red flag that you may be doing something wrong. You can use generics to allow objects that contain other objects to do so generically, like so:
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(1); // Can only add integers, list.add("a string") would fail at compile time
int n = list.get(0); // no need to cast, we know list only contains Integers
If you aren't using a Collection, you'll presumably need to roll your own, as Luke Taylor's answer suggests. That said, you'll get better answers if you can provide more information, the current text of your question doesn't make sense in a Java context.
After seeing your edit, I recommend taking advantage of generics.
When you declare an ArrayList you can indicate what kind of objects it's going to contain.
For example, if you know your ArrayList will contain Strings, you would do this:
List<String> myList = new ArrayList<String>();
If each element of your list is an array of Integers, you would do this:
List<Integer[]> listOfIntegerArrays = new ArrayList<Integer[]>();
Then you could get any element from your list and assign it to an Integer array like this:
Integer[] integerArray = listOfIntegerArrays.get(0);
Then you could iterate over every Integer in the list like this:
for (Integer loopInteger : integerArray) {
System.out.println("The value: " + loopInteger);
}
Some more reading on generics:
http://thegreyblog.blogspot.com/2011/03/java-generics-tutorial-part-i-basics.html
http://docs.oracle.com/javase/tutorial/java/generics/
You could do something like this:
int[] numbersFromObject = new int[yourObject.getAmountOfNumbers()];
// Initialize array with numbers from array
for(int i = 0; i < yourObject.getAmountOfNumbers(); i++) {
numbersFromObject[i] = yourObject.getNumber(i);
}
I'm not sure what methods your object contains, yet I'm sure you'll be able to adjust to the following mentioned above.
I hope this helps.