I have below list defined,
List<BigDecimal> empList = new ArrayList<BigDecimal>();
And as per below code if condition throws error The type of the expression must be an array type but it resolved to List
for(int i1=0;i1<12;i1++) {
if(empList[i1]==null){
empList[i1]= new BigDecimal("0.00");
}
}
The same code works well in Groovy but does not work in Java.
Looks like a syntax error . In java list are accessed as
empList.get(i1)
and
empList.set(i1,new BigDecimal("0.00"))
or you are free to use array instead of List but in this case you will have to define the array length which stays fixed.
BigDecimal[] empList = new BigDecimal[10];
It has to be :
for (int i1 = 0; i1 < 12; i1++) {
if (empList.get(i1) == null) {
empList.set(i1, new BigDecimal("0.00"));
}
}
A list collection needs has its own methods. Use those.
Related
I am trying to replace a value in a List<List<String>> in Java and I am facing this error. I am using List.set() to do this. Basically in my program I am trying to replace the first element of every list in dataList to the variable x.
Below is my code:
for(int i = 0; i <= dataList.size()-1; i++) {
String x = String.join("-","Water",dataList.get(i).get(8).replaceAll("\\s","").split("&")[0],dataList.get(i).get(0));
dataList.set(dataList.get(i).get(0),x);
}
} //end main
But I encountered this error "The method set(int, List<String>) in the type List<List<String>> is not applicable for the arguments (String, String)"
And then I tried converting the sentence to:
dataList.set(Integer.parseInt(dataList.get(i).get(0)),x);
Anyone has any idea how to resolve this ?
you must call set on the inner lists, not the list holding other lists.
It is more like this
for(int i = 0; i <= dataList.size()-1; i++) {
String x = String.join("-","Water",dataList.get(i).get(8).replaceAll("\\s","").split("&")[0],dataList.get(i).get(0));
dataList.get(i).set(0, x);
}
You get list number i and set the first value (0) to x.
Cheers
I have one arraylist that contain two list
like this
[[asd, asswwde, efef rgg], [asd2223, asswwd2323e, efef343 rgg]]
My Code is
ArrayList<String> create = new ArrayList<String>();
ArrayList<String> inner = new ArrayList<String>();
ArrayList<String> inner1 = new ArrayList<String>();
inner.add("asd");
inner.add("asswwde");
inner.add("efef rgg");
inner1.add("asd2223");
inner1.add("asswwd2323e");
inner1.add("efef343 rgg");
create.add(inner.toString());
create.add(inner1.toString());
i have to get all value one by one of every index of that arraylist
So what is the best way to get these all value one by one.
I am using JAVA with Eclipse Mars.
Just use two nested loops:
List<List<Object>> list = ...;
for (List<Object> subList : list) {
for (Object o : subList) {
//work with o here
}
}
You may also want to consider replacing the inner lists by proper objects.
You want to loop through the outside ArrayList and then loop through each ArrayList within this ArrayList, you can do this by using the following:
for (int i = 0; i < outerArrayList.size(); i++)
{
for (int j = 0; j < outerArrayList.get(i).size(); j++)
{
String element = outerArrayList.get(i).get(j);
}
}
Here is another verison you may find easier to understand, but is essentially the same:
for (int i = 0; i < outerArrayList.size(); i++)
{
ArrayList<String>() innerArrayList = outerArrayList.get(i)
for (int j = 0; j < innerArrayList.size(); j++)
{
String element = innerArrayList.get(j);
}
}
or alternatively again using a foreach loop:
for (ArrayList<String> innerArrayList : outerArrayList)
{
for (String element : innerArrayList)
{
String theElement = element;
}
}
It might be worth noting that your ArrayList appears to contain different types of elements - is this definitely what you wanted to do? Also, make sure you surround your strings with "" unless they are variable names - which it doesn't appear so.
EDIT: Updated elements to type String as per your update.
I would also recommend you change the type of your create ArrayList, like below, as you know it will be storing multiple elements of type ArrayList:
ArrayList<ArrayList> create = new ArrayList<ArrayList>();
Try to use for loop nested in foreach loop like this:
for(List list : arrayListOfList)
{
for(int i= 0; i < list.size();i++){
System.out.println(list.get(i));
}
}
I'm not sure if the data structures are part of the requirements, but it would be better constructed if your outer ArrayList used ArrayList as the generic type.
ArrayList<ArrayList<String>> create = new ArrayList<ArrayList<String>>();
ArrayList<String> inner = new ArrayList<String>();
ArrayList<String> inner1 = new ArrayList<String>();
...
create.add(inner);
create.add(inner1);
Then you could print them out like this:
for(List list : create) {
for (String val : list) {
System.out.println(val);
}
}
Othewise, if you stick with your original code, when you add to the outer list you are using the toString() method on an ArrayList. This will produce a comma delimited string of values surrounded by brackets (ex. [val1, val2]). If you want to actually print out the individual values without the brackets, etc, you will have to convert the string back to an array (or list) doing something like this:
for (String valList : create) {
String[] vals = valList.substring(1, val.length() - 1).split(",");
for (String val : vals) {
System.out.println(val.trim());
}
}
I'm trying to create objects within a for loop at runtime. Here is the (incorrect) code:
for(int i=1;i<max;i++){
Object object(i);
}
I'd like it to create max number of Object objects with names object1, object2, etc. Is there any way to do this? I have been unable to find anything elsewhere online. Thanks for your help!
You want to use a data structure to store a sequence of objects. For example, an array could do this:
Fruit banana[] = new Fruit[10];
for (int i = 0; i < 10; i++){
banana[i] = new Fruit();
}
This creates 10 objects of type Fruit in the banana array, I can access them by calling banana[0] through banana[9]
You could use an array to create multiple objects.
public void method(int max) {
Object[] object = new Object[max];
for (int i = 0; i < max; i++) {
object[i] = new Object();
}
}
I am fairly new to Java and am trying to load a LinkedHashMap that contains an ArrayList of values. I am trying to load the values from a query result from an API based query result (Salesforce).
Here is the error: "Cannot refer to a non-final variable breakdown inside an inner class defined in a different method" - the breakdown variable is underlined in red giving this message, Ive noted the line in concern below.
CODE
public LinkedHashMap<String, ArrayList<String>> sfFundIdsByContact;
public ArrayList<String> getFundsIDsForContact(Contact aContact)
{
QueryResult queryResults = null;
ArrayList<String> ids = new ArrayList<String>();
int index = 0;
Boolean done = false;
String contactid = aContact.getId();
String SCCPBId = null;
if(sfFundIdsByContact == null || sfFundIdsByContact.size() <= 0){
//Do the Salesforce API CALL and Return the results
...
while (! done)
{
SObject[] records = queryResults.getRecords();
for ( int i = 0; i < records.length; ++i )
{
if(sfFundIdsByContact.containsKey(breakdown.getSalesConnect__Contact__c())){
sfFundIdsByContact.get(breakdown.getSalesConnect__Contact__c()).add(breakdown.getId());
} else {
//Line below in the add(breakdown.getId() - contains the error
sfFundIdsByContact.put(breakdown.getSalesConnect__Contact__c(), new ArrayList<String>() {{ add(breakdown.getId()); }});
}
}
All suggestions are appreciated.
In your else block, instead of:
new ArrayList<String>() {{ add(**breakdown.getId()**); }}
you can use:
new ArrayList<String>(Arrays.asList(breakdown.getId())
or, since you just want a single element ArrayList, you can use Collections.singletonList that avoids the creation of temporary varargs array:
new ArrayList<String>(Collections.singletonList(breakdown.getId())
The { ... } after the new ArrayList<>() creates an anonymous subclass of ArrayList, which is an inner class only. Inside an inner class you cannot access non-final local variables.
You can ease the code by always retrieving the List value in the for loop, then if it is null create a new one and add it to your Map, otherwise add the value to the list.
for (int i = 0; i < records.length; i++) {
List<String> value = sfFundIdsByContact.get(breakdown.getSalesConnect__Contact__c());
if (value == null) {
value = new ArrayList<String>();
sfFundIdsByContact.put(breakdown.getSalesConnect__Contact__c(), value);
}
value.add(breakdown.getId());
}
As a recommendation, change the definition of
LinkedHashMap<String, ArrayList<String>> sfFundIdsByContact
to
Map<String, List<String>> sfFundIdsByContact
Refer to What does it mean to "program to an interface"?
I'm having an issue understanding some compiler-errors, regarding 2D arrays (ArrayList containing an ArrayList) and generics. My understanding of generics isn't the best, so I tried to research the issue beforehand and still ended up confused.
According to comments on 2D dynamic array using ArrayList in Java, you can't mix arrays with generics (or rather, you can with #SuppressWarnings("unchecked"), but are discouraged from doing so). However, I'm not sure what this exactly means.
Here is my problem code:
blocks = new ArrayList<ArrayList<BarrierBlock>>(columns); // initialize rows
for (int i = 0; i < columns; i++){
// blocks.get(i) = new ArrayList<BarrierBlock>(rows); <- ERROR = (unexpected type; required: variable, found: value)
blocks.add(new ArrayList<BarrierBlock>(rows)); // initialize columns
}
// initilize each block
for (int i = 0; i < blocks.size(); i++){
for (int j = 0; i < blocks.get(i).size(); j++){
int[] blockLoc = {location[0] + (i*BLOCK_SIDE_LENGTH), location[1] + (j*BLOCK_SIDE_LENGTH)};
// blocks.get(i).get(j) = new BarrierBlock(BLOCK_SIDE_LENGTH, blockLoc); <- ERROR = (unexpected type; required: variable, found: value)
blocks.get(i).add( new BarrierBlock(BLOCK_SIDE_LENGTH, blockLoc)); // initialize 2D array elements
}
}
The two lines that I commented out were my initial attempts at initializing the arrays. The compiler complained when I tried this and gave me the error listed. What does this error mean? I would think that both sides are of the declaration statement are variables.
After looking around, I found out that I'm supposed to use the add(E e) method of ArrayList. But what is the main difference? In the new way I'm initializing arrays, doesn't that also "mix arrays with generics"?
Get RETURNS the object at the given index, it can't be used to SET the object.
here are things you CAN do with get:
list l = new list();
item a;
l.add(a);
item b = l.get(0);
b.property = 10;
l.get(0).property == 10; //true, a is the same object as b
b = new item();
l.get(0) == b; //false, list[0] is still a, b is now pointing to a different object
l.get(0) = b; //error, you can't assign to list.get