Using variable name as array index - java

I have few files which I put in array.
I shuffle the files so that it can be displayed in random order.
How to know that array index 0 is actually image1.txt or image2.txt or image3.txt?
Thanks in advance.
String[] a = {"image1.txt","image2.txt","image3.txt"};
List<String> files = Arrays.asList(a);
Collections.shuffle(files);

I'm not sure what you are trying to do.
To access the first element of the shuffled list, use files.get(0).
If you want to know where each element is gone, I suggest you take another approach to it. Create a list of integers from 0 to a.length() - 1, inclusive and shuffle that list. Then manually permute the array a to a new collection.

INCORRECT - see explanation
Note: Arrays.asList() will create a NEW list with the contents of the passed array. The original array will not be modified at all when you use Collections.shuffle().
Explanation
Peter has correctly pointed our that Arrays.asList() does NOT make a copy. The returned list is "write-through" back to the original array. Shuffling the list will shuffle the contents of the original array. Also worth noting that the list is immutable (new elements cannot be added) but typically I find that the use of Arrays.asList() involves immutable lists anyway.
files.get(0); // get the first elements in shuffled list, random
// as greg said
int index = files.indexOf(a[0]); // find out where "image1.txt" is in the list
files.get(index); // get "image1.txt" back from the list

Related

Java array vs Array

It's been a while since I took a proper course on Java and I'm hoping someone can confirm/correct my understanding.
Consider the variables int[] arr and ArrayList arrLi:
arr has pointers directly to each component. arr[3] goes directly to the fourth element whereas arrLi.get(3) would have to traverse through the first three elements to get to the fourth.
Reassigning a component, such as a[3] = 0, does not rewrite the entire array.
Each time you want to add an element to arr, you would need to rewrite the entire array. For example, if there are 100 elements in arr, you have to make a new array with size 101 and copy all the elements from arr then add the new one. If you later decide to add yet another element, you'd have to go through the whole process again to add the 102-nd element.
arrLi adds (to end, front, or middle) and removes elements very efficiently because all it does is add/remove nodes and adjust the links.
ArrayList is a resizable array implementation of the List interface. Therefore fetching an element does not require traversing the previous elements.
Rewriting a value does not require rewriting the entire array in either case.
Yes, an array does need to be recreated if you need more space.
While it is called a list, ArrayList internally behaves much more like an array. ArrayList sometimes needs to be resized, meaning the underlying array needs to be recreated. However, this happens infrequently enough to not affect the average performance of an ArrayList over an array by much.
Please refer to https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html for more information

Array becoming null when List.toArray is used

I'm having an issue where I'm trying to populate an Array with values from a list, then replace the old values with the new ones upon each call of the method. The code below works once, then the next attempt it gives no errors until the new array variable is used , as the array which should have been populated with list data just is full of null values. If anyone has any suggestions much appreciated.
Integer[] stockFF2 =new Integer[ordersBFList.size()];
Integer[] ordersFF2 =new Integer[stockBFList.size()];
stockFFList.toArray(stockFF2);
ordersFFList.toArray(ordersFF2);
I think you have got the sizes wrong (orderFF2 and stockFF2 are using the sizes of each other's lists). I suspect one of the arrays is populated properly - one with the larger array - while the other allocates and returns a new array with the elements you want keeping the passed in array as it was because it is too short.
The toArray() method makes a fresh array and copies the contents of the list into it.
Try
Integer[] stockFF2 = stockBFList.toArray();
Integer[] ordersFF2 = ordersBFList.toArray();
If you want to reuse these arrays (seldom worthwhile), then replace their values with:
stockFF2 = stockBFList.toArray(stockFF2);
ordersFF2 = ordersBFList.toArray(ordersFF2);
It's unsafe to ignore the return value. If the source Collections get larger, the return value is another fresh array.

How to add an element at the end of an array?

I want to know how to add or append a new element to the end of an array. Is any simple way to add the element at the end? I know how to use a StringBuffer but I don't know how to use it to add an element in an array. I prefer it without an ArrayList or list. I wonder if the StringBuffer will work on integers.
You can not add an element to an array, since arrays, in Java, are fixed-length. However, you could build a new array from the existing one using Arrays.copyOf(array, size) :
public static void main(String[] args) {
int[] array = new int[] {1, 2, 3};
System.out.println(Arrays.toString(array));
array = Arrays.copyOf(array, array.length + 1); //create new array from old array and allocate one more element
array[array.length - 1] = 4;
System.out.println(Arrays.toString(array));
}
I would still recommend to drop working with an array and use a List.
Arrays in Java have a fixed length that cannot be changed. So Java provides classes that allow you to maintain lists of variable length.
Generally, there is the List<T> interface, which represents a list of instances of the class T. The easiest and most widely used implementation is the ArrayList. Here is an example:
List<String> words = new ArrayList<String>();
words.add("Hello");
words.add("World");
words.add("!");
List.add() simply appends an element to the list and you can get the size of a list using List.size().
To clarify the terminology right: arrays are fixed length structures (and the length of an existing cannot be altered) the expression add at the end is meaningless (by itself).
What you can do is create a new array one element larger and fill in the new element in the last slot:
public static int[] append(int[] array, int value) {
int[] result = Arrays.copyOf(array, array.length + 1);
result[result.length - 1] = value;
return result;
}
This quickly gets inefficient, as each time append is called a new array is created and the old array contents is copied over.
One way to drastically reduce the overhead is to create a larger array and keep track of up to which index it is actually filled. Adding an element becomes as simple a filling the next index and incrementing the index. If the array fills up completely, a new array is created with more free space.
And guess what ArrayList does: exactly that. So when a dynamically sized array is needed, ArrayList is a good choice. Don't reinvent the wheel.
The OP says, for unknown reasons, "I prefer it without an arraylist or list."
If the type you are referring to is a primitive (you mention integers, but you don't say if you mean int or Integer), then you can use one of the NIO Buffer classes like java.nio.IntBuffer. These act a lot like StringBuffer does - they act as buffers for a list of the primitive type (buffers exist for all the primitives but not for Objects), and you can wrap a buffer around an array and/or extract an array from a buffer.
Note that the javadocs say, "The capacity of a buffer is never negative and never changes." It's still just a wrapper around an array, but one that's nicer to work with. The only way to effectively expand a buffer is to allocate() a larger one and use put() to dump the old buffer into the new one.
If it's not a primitive, you should probably just use List, or come up with a compelling reason why you can't or won't, and maybe somebody will help you work around it.
As many others pointed out if you are trying to add a new element at the end of list then something like, array[array.length-1]=x; should do. But this will replace the existing element.
For something like continuous addition to the array. You can keep track of the index and go on adding elements till you reach end and have the function that does the addition return you the next index, which in turn will tell you how many more elements can fit in the array.
Of course in both the cases the size of array will be predefined. Vector can be your other option since you do not want arraylist, which will allow you all the same features and functions and additionally will take care of incrementing the size.
Coming to the part where you want StringBuffer to array. I believe what you are looking for is the getChars(int srcBegin, int srcEnd,char[] dst,int dstBegin) method. Look into it that might solve your doubts. Again I would like to point out that after managing to get an array out of it, you can still only replace the last existing element(character in this case).
one-liner with streams
Stream.concat(Arrays.stream( array ), Stream.of( newElement )).toArray();

Randomly inspecting an object in an arraylist

I have an arraylist full of different types of an object. (i.e an objects that extend a superobject)
an example is:
{object1,
object1,
object2,
object3}
Now what I need to do is effectively pull a random object out of the array list. If it matches a set of criteria it will then run a method of this object. Otherwise it will run again till it finds an object till it does.
Now the reason why I can't just go over the objects from start to finish is because I need to provide some form of distribution.
How would I go about this? I know how to iterate over an array list, but Randomly inspecting an object in an array is out of my scope.
This is quite easy using the Random class. Since I don't know what object you are working with, I'll show you an example where you want to randomly search a list of integers until you find one that is less than 10.
ArrayList<int> list = new ArrayList<int>();
Random random = new Random();
do{
int randomlyChosenInt = list.get(random.nextInt(list.Size()));
while(int >= 10);
One way is to shuffle with Collections.shuffle(), then iterate.
Another way is to pick a random element, swap it with the last one, remove it from list and then check. The advantage is that you don't have to swap N time like shuffle does - you only swap until you found a satisfactory element.
Instead of picking random elements, shuffle the array once and then iterate over the result:
Collections.shuffle(objects);
for (Object o : objects) {
// you are now accessing objects in random order
}

Copy array without redundancy

I have two arrays in my program. One is full(with redundant items in it). I want to copy all the items to the second empty array without redundancy. The only problem I have is "how to declare size of the second array?" Because Iam not sure how many are the redundant items in the first array.
I would use Set for this, that will remove duplicates from your array and you convert then back to array or another collection of you need that.
Set<Item> withoutDups = new HashSet<Item>(Arrays.asList(yourArray));
//now you have it without duplicates and do whatevet you want with it:-)
Item[] arrayWithoutDups = new Item[withoutDups.size()];
withoutDups.toArray(arrayWithoutDups); // fill the array
Convert string array to list. Use a LinkedHashSet to eliminate duplicates. The LinkedHashSet maintains insertion order along with uniqueness.
Edit: I have removed the List as it is redundant.
String[] words = {"ace", "ace","boom", "crew", "dog", "eon"};
Set<String> hs = new LinkedHashSet<String>(Arrays.asList(words));
String[] mywords=hs.toArray(new String[hs.size()]);
for(int i=0;i<mywords.length;i++)
{
System.out.println("..."+mywords[i]);
}
Arrays are of fixed size. You should use ArrayList in this case.
However, if you have to use an array then you should allocate the size of 2nd array equal to the size of 1st array because it may contain no redundant elements at all.
Use ArrayList which size can be smaller than original array, then create array from it, if needed.
So what's the problem ?
Loop through values in source array, find number of redundant items. Then allocate second array and in next loop copy values.
Complexity of this approach is 2n=O(n)
Since you don't know which item are redundant you need to loop over your array. I suggest that you use temporary List uniqueItemsList to add the items during your loop.
The list will grow as needed.
Then you can get a array with code like this (replace String with your type) :
String uniqueItems[] = new String[uniqueItemsList.size()];
uniqueItems = uniqueItemsList.toArray(uniqueItems);

Categories