This question already has answers here:
How to change value of ArrayList element in java
(7 answers)
Closed 8 years ago.
How do I swap the the first and last elements of an ArrayList?
I know how to swap the elements of an array: setting a temporary value to store the first element, letting the first element equal the last element, then letting the last element equal the stored first element.
int a = values[0];
int n = values.length;
values[0] = values[n-1];
values[n-1] = a;
So for an ArrayList<String> would it be like this?
String a = words.get(0);
int n = words.size();
words.get(0) = words.get(n-1);
words.get(n-1) = a
You can use Collections.swap(List<?> list, int i, int j);
In Java, you cannot set a value in ArrayList by assigning to it, there's a set() method to call:
String a = words.get(0);
words.set(0, words.get(words.size() - 1));
words.set(words.size() - 1, a)
Use like this. Here is the online compilation of the code. Take a look http://ideone.com/MJJwtc
public static void swap(List list,
int i,
int j)
Swaps the elements at the specified positions in the specified list. (If the specified positions are equal, invoking this method leaves the list unchanged.)
Parameters:
list - The list in which to swap elements.
i - the index of one element to be swapped.
j - the index of the other element to be swapped.
Read The official Docs of collection
http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#swap%28java.util.List,%20int,%20int%29
import java.util.*;
import java.lang.*;
class Main {
public static void main(String[] args) throws java.lang.Exception
{
//create an ArrayList object
ArrayList words = new ArrayList();
//Add elements to Arraylist
words.add("A");
words.add("B");
words.add("C");
words.add("D");
words.add("E");
System.out.println("Before swaping, ArrayList contains : " + words);
/*
To swap elements of Java ArrayList use,
static void swap(List list, int firstElement, int secondElement)
method of Collections class. Where firstElement is the index of first
element to be swapped and secondElement is the index of the second element
to be swapped.
If the specified positions are equal, list remains unchanged.
Please note that, this method can throw IndexOutOfBoundsException if
any of the index values is not in range. */
Collections.swap(words, 0, words.size() - 1);
System.out.println("After swaping, ArrayList contains : " + words);
}
}
Oneline compilation example http://ideone.com/MJJwtc
for (int i = 0; i < list.size(); i++) {
if (i < list.size() - 1) {
if (list.get(i) > list.get(i + 1)) {
int j = list.get(i);
list.remove(i);
list.add(i, list.get(i));
list.remove(i + 1);
list.add(j);
i = -1;
}
}
}
Related
I created a method which takes an Arraylist of string and an integer. It's going to remove all string whose length is less than the given integer.
For example:
Arraylist = ["abcde", "aabb", "aaabbb", "abc", "ab"]
integer = 4
So the new Arraylist should be: ["abcde", "aabb", "aaabbb"]
But I'm getting this error message:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 3 out of bounds for length 3
Here is my code:
public static void main(String[] args){
ArrayList<String> newArrayList = new ArrayList<>();
newArrayList.add("string1");
newArrayList.add("string2");
newArrayList.add("rem");
newArrayList.add("dontremove");
removeElement(newArrayList, 4); // new arraylist must be = [string1, string2, dontremove]
}
public static void removeElement(ArrayList<String> arraylist, int inputLen){
int arrayLen = arraylist.size();
for(int i=0; i<arrayLen; i++){
if(arraylist.get(i).length() < inputLen){
arraylist.remove(i);
i--;
}
}
System.out.println("New Arraylist: " + arraylist);
}
What's wrong with this code?
You're looping from 0 to the size of the array which is 4. Inside the loop you're removing items so the size of the array becomes less than 4, so you get this exception.
Try looping like this:
Iterator<String> iterator = arraylist.iterator();
while (iterator.hasNext()) {
String word = iterator.next();
if (word.length() < inputLen) {
iterator.remove();
}
}
You're modifying the list while iterating over its indexes. Once you remove the first item, the list will be shorter than you expect, and you'll get this error once you reach the index of the original last element. Luckily, the removeIf method can do the heavy lifting for you:
public static void removeElement(List<String> arraylist, int inputLen) {
arraylist.removeIf(s -> s.length() < inputLen);
System.out.println("New Arraylist: " + arraylist);
}
The length of the array should change when you remove elements. The arrayLen variable stores the length of the array, but doesn't change when the array's length shrinks. To change it, you should be able to just replace arrayLen with arrayList.size(), which will change when your remove elements
int arrayLen = arraylist.size();
The problem is that your index has a value of 4.
But then as soon as you remove an item from the list you now only have 3 entries.
So in your loop when you try to access the the 4th entry you will now get an IndexOutOfBounds error.
The solution is to start at the end of the ArrayList and count down to 0.
For (int i = arrayLen - 1; i >= 0; i--)
and inside the loop you don't need the:
i--;
This question already has answers here:
After ArrayList.add() in a loop, all elements are identical. Why? [duplicate]
(3 answers)
Closed 2 years ago.
I want to get different array elements combinations (permutations) of an array to a List. I swap the first and the last element of the array through a for loop and the combination (permutation) is added to the List. Then the second and the element before the last is swapped and added to the List, so and so forth. Suppose the array is arr[1,2,3,4,5,6,7], the first element added to the List would be arr[7,2,3,4,5,6,1]. The second element would be arr[7,6,3,4,5,2,1]. But what I end up getting is something like arr[7,6,5,4,3,2,1] for all the elements in the List.
The problem is that the elements added to the List are also modified correspondingly with the current modification of the array. I end up getting similar array elements in the List. What I want is different permutations or arrays with different combinations of elements. Can you please help me with this?
private List<Gate[]> generateSolutions(Gate[] solution) {
List<Gate[]> sList= new ArrayList<>();
int i, j;
for (i = 0, j = solution.length - 1; i < solution.length / 2; i++, j--) {
Gate temp;
temp = solution[i];
solution[i] = solution[j];
solution[j] = temp;
sList.add(solution);
}
return sList;
}
import java.util.ArrayList;
import java.util.List;
/**
* Dev Parzival
* Date : 27/10/2020 Time : 22:40
* I have a confidence about my life that comes from standing tall on my own two feet.
*/
public class Permutation {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<>(10);
//Make sure that the list has unique numbers
for(int i=0;i<3;i++)
list.add(i+1);
int n =list.size();
Permutation permutation = new Permutation();
//Generater permutation
permutation.permute(list, 0, n-1);
}
private void permute(ArrayList<Integer> list, int l, int r) {
//When l is equal to one less than the length of the list we will display it.
if (l == r)
System.out.println(list);
else{
//The l valuse specifies which position we want to fix
for (int i = l; i <= r; i++) {
//After diciding the position we fix it by swapping it.
swap(list,l,i);
//Here we are fixing l+1 th number
permute(list, l+1, r);
//Swapping it back to its original position so initial order is maintained
swap(list,l,i);
}
}
}
//Swap function will swap ith and jth numbers of the list
private void swap(List<Integer> list, int i, int j) {
int temp=list.get(i);
list.set(i,list.get(j));
list.set(j,temp);
}
}
Above code is used for generating permutation.
I am only editing the bottom methods for this assignment. I am trying to increase every element of the list by n or "value" elements but I can't seem to figure out how. This is my approach so far. There is a method for finding the min not shown that works as intended. I am only trying to modify the body of the second method
public class ArrayListLab
{
public static void main(String[] args)
{
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(12);
list.add(45);
list.add(23);
list.add(48);
list.add(11);
System.out.println("Original list is " + list);
System.out.println("The smallest value is " + minimum(list)); // Expected: 11
modifyList(list, 5);
System.out.println("The new list is " + list);
}
public static void modifyList(List<Integer> list, int value)
{
for(int i = 0; i < value; i++);
list.get(i) += value;
}
I think you need to update your for loop to go from 0 to the length of list (for(int i = 0; i < list.size(); i++)) instead of go from 1 to value (for(int i = 0; i < value; i++)). You also need to remove the ; at the end of for statement so the Java program will take the list update code below instead of looping through an empty block of code.
Regarding how to update an ArrayList object, you can use the setfunction for that (list.set(i, list.get(i) + value))
public static void modifyList(List<Integer> list, int value) {
for(int i = 0; i < list.size(); i++)
list.set(i, list.get(i) + value);
}
Update: To rotate the ArrayList like you mention, you can remove and return the first element in the list using the function remove(0) and the just add it to end of the list using the add function like you did in the main function
public static void rotateList(List<Integer> list, int n) {
for(int i = 0; i < n; i++)
list.add(list.remove(0));
}
You should iterate over the list.
public static void modifyList(List<Integer> list, int value)
{
for(int i = 0; i < list.size(); i++){
list.set(i, list.get(i) + value);
}
}
In your code there are 2 errors
Logical
Syntax
Syntax for(int i = 0; i < value; i++); there's a ; and cause of that your variable i wont get recognized or say it would be out of scope.
Logical:
When you did list.get(i) all it does is, Gives you the value associated with that index.
You can do like int sum = list.get(i) + value what this will do it get the value from the list at index i and then add the number 5 to it. So now your sum holds value from index i + 5 which you wanted.
Now all you gotta do it set the index at i to the sum we calculated.
When we do list.set(i, sum) it overwrites the value at that index with our sum.
public static void modifyList(ArrayList<Integer> list, int value)
{
for(int i = 0 ; i < value ;i++) {
int sum = list.get(i) + value;
list.set(i,sum);
}
}
So you have a couple of problems, first in the method modifyList() the parameter List<Integer> should actually be ArrayList<Integer>. Furthermore, your for loop must have a { instead of ; at the end of the line.
An easier way to loop through ArrayLists is
for(Integer i : list) {list.set(i, i+value); }
Also, the minimum(list) is undefined.
Check out https://www.w3schools.com/java/java_arraylist.asp for help on arraylists
This question already has answers here:
Iterating through a Collection, avoiding ConcurrentModificationException when removing objects in a loop
(31 answers)
Closed 10 years ago.
I have array list of strings. I want to check in specific moment if in this array I have more elements than my "i", if yes I want to remove that elements. For example. I have five elements in array. I choose element which index is four. I want to check if exist higher element(in this case that higher will be element which index is 5) and remove that element. If I choose 3 element I want to remove 4 and 5 element. I do something like that:
for(int j = 0; j<descriptions.size();j++){
if(!descriptions.get(i+1).isEmpty()){
descriptions.remove(i+1);
}
}
This solution work good when I choose 3 element and two elements was removed. But when I want choose 4 element I get index out of bound exception. How I can solve my problem?
I don't quite see the point of using for loop in your code.
What you probably want to do is to remove any items beyond i th element in the list.
The easiest way to do is to repeatedly remove the last element from the list.
Here's a sample code for reference:
while(descriptions.size() > i){
descriptions.remove(descriptions.size()-1);
}
public static void main(String[] args) {
//list of string with 5 elements
List<String> descriptions = new ArrayList<String>();
descriptions.add("first");
descriptions.add("second");
descriptions.add("third");
descriptions.add("4");
descriptions.add("5");
//the size you want to check for the list
int i = 3;
int howMuchToRemove = descriptions.size()-i;
//if the list how more object from > i , we will remove objects from it
if (howMuchToRemove > 0)
for (int j=0 ; j < howMuchToRemove ; j++)
//remove the last object in the list
descriptions.remove(descriptions.size()-1);
System.out.println(descriptions.toString());
}
I have five elements in array. I choose element which index is four.
The fifth element is at index 4. if you want to choose the 4th element, it's index will be 3.
Modify your code as following:
int size = descriptions.size();
for(int j = size -1; j>choosenNum; j--)
{
descriptions.remove(j);
}
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<String>();
list.add("a");
list.add("a");
list.add("a");
list.add("a");
list.add("a");
indexToRemove(list, 5);
}
private static void indexToRemove(ArrayList<String> list, int index) {
if (list.size() > index) {
list.remove(index);
System.out.println(index + "th item removed");
} else
System.out.println("Can't remove");
}
You mean a function which will remove the given index element? then try this.
for(int i = descriptions.size()-1; i > indexToDeleteAfter; i--){
descriptions.remove(i);
}
Or, defer to ArrayList:
if(descriptions.size() - 1 > indexToDeleteAfter)
{
descriptions.removeRange(indexToDeleteAfter + 1, descriptions.size() - 1);
}
http://docs.oracle.com/javase/1.4.2/docs/api/java/util/ArrayList.html#removeRange(int,%20int)
Here's what the layout is
index num
0 [10]
1 [20]
2 [30]
(Add 35 here)
3 [40] Move elements down
4 [50]
5 [60]
6 [70]
then my method is this
public static void method(int[] num, int index, int addnum)
{
}
How can i add 35 in there?
Tried this:
public static void method(int[] num, int index, int addnum)
{
int index = 10;
for(int k = num.length k>3; k++)
{
Num[k]=num[k++]
}
Num[3] = 35;
As this is something you should accomplish yourself, I will only provide the method to implement it, not the code:
If you would set the number at position index, you would overwrite the value that was there previously. So what you need to do is move every element one position towards the end of the array starting from index: num[x] becomes num[x+1], etc.
You will find out that you need to do this in reverse order, otherwise you will fill your array with the value in num[index].
During this process you will need to decide what to do with the last entry of the array (num[num.length - 1]):
You could just overwrite it, discarding the value
You could return it from your function
You could throw an exception if it is non-zero
You could create a new array that is 1 entry larger than the current array instead to keep all values
etc.
After this, you have duplicated num[index]: the value is present in num[index+1], too, as you have moved it away.
Now it is possible to write the new value at the desired position without overriding an existing value.
EDIT
You have several errors in your code:
You increment k, you need to decrement it (k--, not k++)
You modify k again in your loop body: it is updated twice in each cycle
If you start with k = num.length, you will try to write at num[num.length + 1], which is not possible
Very crudely, you want to do something like this:
public static void(int[] num, int index, int addnum)
{
// initialize new array with size of current array plus room for new element
int[] newArray = new int[num.length + 1];
// loop until we reach point of insertion of new element
// copy the value from the same position in old array over to
// same position in new array
for(int i = 0; i < index; i++)
{
newArray[i] = num[i];
}
i = i + 1; // move to position to insert new value
newArray[i] = addnum; // insert the value
// loop until you reach the length of the old array
while(i < num.length)
{
newArray[i] = num[i-1];
}
// finally copy last value over
newArray[i + 1] = num[i];
}
You need to
allocate a new array with room for one new element.
int[] newArray = new int[oldArray.length + 1];
Copy over all elements and leave room for the one to insert.
for (int i = 0; i < newArray.length - 1; i++)
newArray[i < insertIndex ? i : i + 1] = oldArray[i];
Insert 35 in the empty spot.
newArray[insertIndex] = numberToInsert;
Note that it's not possible to do in a method like this:
public static void method(int[] num, int index, int addnum)
^^^^
since you can't change the length of num.
You need to allocate a new array, which means that need to return the new array:
public static int[] method(int[] num, int index, int addnum)
^^^^^
and then call the method like this:
myArr = method(myArr, 3, 35);
Since this very closely resembles homework what you need to realize is that you cannot dynamically increase the size of an array. So in your function:
public static void(int[] num, int index, int addnum)
{
int[] temp = new int[num.length *2];
for(int i = 0; i < index; i++)
copy num[i] into temp[i]
insert addnum into temp[index]
fill temp with remaining num values
}
That pseudocode above should get you started.
What you're looking for is an insertion sort.
It's classwork, so it's up to you to figure out the proper code.
Well, you can't unless there is "extra space" in your array, and then you can shift all elements [starting from index] one element to the right, and add 35 [num] to the relevant place.
[what actually happen is that the last element is discarded out].
However - a better solution will probably be to use an ArrayList, and use the method myArrayList.add(index,element)
How about this?
public class test {
public static void main(String[] arg) throws IOException
{
int[] myarray={1,2,3,5,6};//4 is missing we are going to add 4
int[] temp_myarray=myarray;//take a temp array
myarray=addElement(myarray,0);//increase length of myarray and add any value(I take 0) to the end
for(int i=0;i<myarray.length;i++)
{ if(i==3) //becaues I want to add the value 4 in 4th place
myarray[i]=4;
else if(i>3)
myarray[i]=temp_myarray[i-1];
else
myarray[i]=temp_myarray[i];
}
for(int i=0;i<myarray.length;i++)
System.out.print(myarray[i]);//Print new array
}
static int[] addElement(int[] arr, int elem) {
arr = Arrays.copyOf(arr, arr.length + 1);
arr[arr.length - 1] = elem;
return arr;
}
}