I want to find a index of an array in array list such that,
String[]names=new String[x];
new ArrayList<String>(Arrays.asList(names));
int w=......indexOf(search);
I don't know what am I going to suppose to write on ......
The List interface has the indexOf method:
Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element
So, you just need to invoke this method.
Note that
new ArrayList<String>(Arrays.asList(names));
creates a List (two Lists, actually), but doesn't actually store the created list anywhere; so you don't end up with anything you can invoke the method on.
Either:
List<String> list = new ArrayList<String>(Arrays.asList(names));
int w = list.indexOf(search);
or:
int w = new ArrayList<String>(Arrays.asList(names)).indexOf(search);
or, even easier, since Arrays.asList returns a List, and you don't need to mutate the list to search it:
int w = Arrays.asList(names).indexOf(search);
Related
For a sublist of an ArrayList, how do I get the sublist including the last element in the list? If I'm using the wrong method, can you direct me towards the correct one?
list.subList(startIndex, index + list.size()) // obviously doesn't work, outside of range
list.sublist(startIndex) // doesn't work because this method requires two parameters
You can find the correct method including a description in the JavaDoc:
https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/AbstractList.html#subList(int,int)
public List<E> subList(int fromIndex,
int toIndex)
With this method, you can create a new list including all the elements from an existing list, you want to have in your new list.
Example: final var newList = oldList.subList(7, oldList.size());
This will create a new list containing the objects from position 8 to the end of the old list.
How can I count number of elements stored in different position in a list.
Eg :
final List<String> products = new ArrayList<>();
products .set(2,"Top");
products .set(5,"Bottom");
products .set(7,"Pants");
products .set(10,"Skirt");
Count should be 4.
Is there any short solution for this.
E set(int index, E element) method replaces element of specific index. If list does not have element at that position it will throw IndexOutOfBoundsException. Moreover, if you want to find number of elements in list you can simply use size().
Use this:
int c=products.size();
In your case,c will be assigned a value 4 since you have 4 elements in your list.
Note:
The first index of your array list is 0 and it goes in order-0,1,2....etc.
You need to place something at the indices 0 and 1 before going to 2.You can't skip to 2.
In your case,it will throw an error because you are replacing the element at a position/index using the set(int index,string new) without assigning an element to that position.
The positions are already empty and so there is nothing to replace.
Use products.add(int index,String new) to assign a value to a particular index.Replace set with add in your code.Begin with index 0.
Finally,use the product.size() to get the number of elements.
The data structure appropriate to your task is Map. You can use it like this:
Map<Integer, String> products = new HashMap<>();
products.put(2,"Top");
products.put(5,"Bottom");
products.put(7,"Pants");
products.put(10,"Skirt");
String p10 = products.get(10); // "Skirt"
int productCount = products.size(); // 4
boolean has3 = products.containsKey(3); // false
I'm writing a method that removes an element from an ArrayList of strings, if it is of a given length, and puts the removed String into an Array containing Strings, and I'm a bit confused at how to insert elements into the array after removing them from the List.
My ArrayList is called list, and it's an instance variable in the beginning of my program.
public String[] removeOfLength(String [] arr, int wordLength)
{
arr = new String[list.size()];
for(int i = 0; i < list.size(); i++)
{
if(list.get(i).length == wordLength)
{
list.remove(i);
//arr[i]
}
}
}
I removed the element, but I don't know how to insert it into the array.
The method is supposed to return a String array containing the removed Strings.
Instead of creating an array first, which has to be as long as the list itself, use a list again to hold the removed strings temporarily.
List<String> removedStrings = new ArrayList<String>();
for(int i = 0; i < list.size(); i++)
{
if(list.get(i).length == wordLength)
{
removedStrings.add(list.remove(i));
}
}
Then just convert the list into an array when the method ends
return removedStrings.toArray(new String[removeStrings.size()]);
Just assign the value at a certain index.
Also the remove method returns the value removed from the list.
arr[I]=list.remove(I);
Also you need to return arr at the end of the method. And if the method calling this one expects the array that its providing as an argument to have the elements it won't because you are assigning it a new reference at the beginning.
Also, the array will not fill like a list, there will be gaps if it doesn't remove every element from your list, arrays aren't smart like ArrayLists.
Since array is a fixed length structure and you have to specify the length at the creation, you cannot directly insert removed element to a new array because you don't know how many elements will be there in array.
Instead, you can use the arraylist to keep removed elements temporarily and at the end of the iteration, populate those to a new array (because at that point, you know the length of the array using number of elements in your temporary arraylist).
In one of my methods, I need to pass objects as variable length parameters.
However, first I need to process the last object and then based on that many other processing will be done. I could not figure out how to use the index for each of the items in the variable argument list using traditional for loop and then index. So I used below code. Is this the right method to copy the object reference to another Array or ArrayList as I did? Otherwise what is the best method to access the specific object first and then loop through all other objects.
public static int generateConnectedPatterns(String endStr,Moorchana.MoorchanInnerClass...totalPatterns) {
// First copy all the objects to new ArrayList or Array of objects
ArrayList <Moorchana.MoorchanInnerClass> objectList = new ArrayList<>();
objectList.addAll(Arrays.asList(totalPatterns));
//Temporarily use lastObject variable for convenience.
Moorchana.MoorchanInnerClass lastObject = objectList.get(objectList.size()-1);
// Split the last input string into swaras
ArrayList<Integer> indices = new ArrayList<>();
ArrayList<String> tempPatternList = new ArrayList<>();
splitInputPatternIntoArrayList(tempPatternList , indices, lastObject.rawInputString);
if (Moorchana.validatePresenceInSwaraPool(endStr, lastObject.returnOuterObjectRef().swaraPool) == -1) {
return (-1);
}
// Get the index of the ending String
int indexofEndStr = lastObject.returnOuterObjectRef().getSwaraIndex(endStr);
// Now get the number of patterns to be generated.
int count = lastObject.returnOuterObjectRef().getPatternCount(indices, indexofEndStr);
// Now Do remaining programming here based on the count.
return(Constants.SUCCESS);
}
A varargs is basically an array.
Once you checked for null and length, you can access the last element just as you would with an array.
On the other hand, Arrays.asList returns a fixed-size list, which means you will not be able to manipulate its size later on, so beware of UnsupportedOperationExceptions.
In short, you can use the varargs as array and reference the last element once the necessary checks are performed.
Treat totalPatterns as an array.
To identify the last element: totalPatterns[totalPatterns.length-1]
for iteration, you could use an enhanced for loop.
for ( Moorchana.MoorchanInnerClass d : totalPatterns){...}
Note: Do a null check before you process the array, if you are not sure of the input being passed.
I have an ArrayList of integers, as such;
ArrayList<Integer> list = new ArrayList<>();
list.add(8);
list.add(20);
list.add(50);
I also have a variable, that is set to a random item from that ArrayList. I want to remove the item in the variable from the arraylist, so I tried this;
list.remove(var);
However, it assumes that because var is an integer, it tries to get the index at the location of var instead of searching for and removing it. But because every item in the list is larger than the size of it, it always gives an ArrayOutOfBoundsException. Is there a way to force Java to attempt to use the proper remove method?
You need to pass an Integer - your main options are:
Integer valueToRemove = 8;
list.remove(valueToRemove);
int anotherOne = 20;
list.remove(Integer.valueOf(anotherOne));
int andFinally = 50;
list.remove((Integer) andFinally);
When you call add(8), it is actually autoboxed so the actual call is add(new Integer(8)). That doesn't happen on the remove() call because there's actually a remove() call that takes an int as an argument. The solution is to create the Integer object yourself instead of relying on autoboxing: list.remove(new Integer(var)).