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.
Related
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);
I am Passing an Array into a for loop with an if statment, I am want to have all the elements that evaluate true be added to a new array. How Do I do This?
Supposing you have an object array, and you want to create a possibly smaller array containing the elements that satisfy some predicate, you are faced with the problem of knowing how big to make the new array. You can determine that only by testing each starting element against the predicate, which you would normally prefer to avoid doing twice. One way to approach the problem would be to use a List to temporarily hold the elements you want to collect:
MyElementType[] myArray = { /* ... */ };
MyElementType[] result;
List<MyElementType> temp = new ArrayList<MyElementType>();
for (MyElementType element : myArray) {
if (passesMyTest(element)) {
temp.add(element);
}
}
result = temp.toArray(new MyElementType[0]);
Of course, it's usually easier to work directly with Lists instead of with arrays, but sometimes you don't have that luxury.
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).
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)).
I have an array for example:
String [][] test = {{"a","1"},
{"b","1"},
{"c","1"}};
Can anyone tell me how to remove an element from the array. For example I want to remove item "b", so that the array looks like:
{{"a","1"},
{"c","1"}}
I can't find a way of doing it. What I have found here so far is not working for me :(
You cannot remove an element from an array. The size of a Java array is determined when the array is allocated, and cannot be changed. The best you can do is:
Assign null to the array at the relevant position; e.g.
test[1] = null;
This leaves you with the problem of dealing with the "holes" in the array where the null values are. (In some cases this is not a problem ... but in most cases it is.)
Create a new array with the element removed; e.g.
String[][] tmp = new String[test.length - 1][];
int j = 0;
for (int i = 0; i < test.length; i++) {
if (i != indexOfItemToRemove) {
tmp[j++] = test[i];
}
}
test = tmp;
The Apache Commons ArrayUtils class has some static methods that will do this more neatly (e.g. Object[] ArrayUtils.remove(Object[], int), but the fact remains that this approach creates a new array object.
A better approach would be to use a suitable Collection type. For instance, the ArrayList type has a method that allows you to remove the element at a given position.
There is no built-in way to "remove" items from a regular Java array.
What you want to use is an ArrayList.
You could set the entry in the array to null (test[0][1] = null;). However, "removing" the item such that the array will have one element less than before is not doable without recreating the array. If you plan to change data in the data structure regularly an ArrayList (or another Collection class depending on your needs) might be more convenient.
My solution is:
You cannot remove an element from an array => it's correct, but we can do something to change current array.
No need assign null to the array at the relevant position; e.g.
test[1] = null;
Create a new array with the element removed; e.g.
String[][] temp = new String[test.length - 1][];
Need to get index at string/array to remove: IndexToRemove
for (int i = 0; i < test.length-1; i++) {
if (i<IndexToRemove){
temp[i]=test[i];
}else if (i==IndexToRemove){
temp[i]=test[i+1];
}else {
temp[i]=test[i+1];
}
}
test = temp;
Hope it helpful!