How to shuffle a file[] using java collections? - java

I am sure I missed something in my reading but I can't figure this out. My program gets a list of image files from a directory and then selects files at random to display as part of the game. The problem is, every time I have ran it using a random number generator it has duplicate numbers. In reading I saw Collections and I think that will work for me as it randomly shuffles the list. This eliminates the need for a random number generator. My problem is that I can not figure out how to get it to shuffle the File[].
This is the last thing I tried
comboFile = filePath.listFiles();
List listShuffle = new List();
listShuffle = (List) Arrays.asList(comboFile);
Using list without gets rid of that error but now the Collections.shuffle method is giving me an error. No suitable nethod found for shuffle(java.awt.list)
Collections.shuffle(listShuffle);
How do I turn the File array into a list to shuffle?

The problem seems to be that listShuffle is never used after shuffling it. You are still reading the values from the comboFile array, which is never shuffled.
Also, it should be Arrays.asList() instead of Array.asList().

You're using the wrong type. Change your import to java.util.List instead of java.awt.List. The error is telling you there is no method that accepts the list type you're passing in.
And yes, you probably want to create the list using Arrays.asList() like the other guys suggested.

Please try Arrays.asList() function.
It will make a wrapper of the array. And call shuffle() function, which will change the inside array elements' order.

Related

How to create ArrayList without using add-function

As the title implies, I'd like to know how to insert different values into my ArrayList, without using too much space for several "add" functions.
ArrayList<Integer> arr = new ArrayList<Integer>(Arrays.asList(3,4));
ArrayCheck.allDivisibleBy(arr, divisor);
I have got an arraylist called arr, and I don't know if this is the right way to add several values (3,4) that way.
Furthermore I would also like to check the values in another method called allDivisbleBy. The function of this method is not relevant though, but I want to check the values and am not sure if "ArrayCheck" is a way to send the array values to the method.
The simplest way is to use Arrays.asList(arr). As expected, that static method returns a List with as it's contents the elements of the array.
I don't know if this is the right way to add several values (3,4) that
way
Yes it is. Else you can use this:
ArrayList<Integer> arr = new ArrayList<Integer>(2);
arr.add(3);
arr.add(4);
I want to check the values and am not sure if "ArrayCheck" is a way to
send the array values to the method
ArrayCheck is not a standard java class.
Check all of your inputs for your condition, put them in a Collection and use method addAll instead of add to add all of collection items at once.

Size has private access in ArrayList

I wrote a pretty standard bit of code utilizing String populated ArrayList but when I try running it, I get the following error:
error: size has private access in ArrayList.
The code is as follows:
System.out.println(testedArticles.size);
You are attempting to access a private member of ArrayList, part of its internal working that are not supposed to be used externally
If you want to get the size of the arraylist you want the method:
arraylist.size()
Why is it like this
This gives the ArrayList class the option to store size in whatever way it wants. Does it just return size, probably, but it could do a number of other things instead. For example it could calculate size lazily, in which it is only calculated if someone asked for it then it stores that value until it becomes invalid (as more objects are added). This would be useful if calculating size was expensive (very unlikely to be the case here), changed often and was called only occasionally.
There is nothing like ArrayList.size. You need to use .size() method.
You need to use
System.out.println(testedArticles.size());
instead of
System.out.println(testedArticles.size);

Get the index of an object I just added to an ArrayList in Java/Android

I want to load a series of objects to an ArrayList, and return the index of where it was added so it can be used later directly from the ArrayList. It'd be akin to me loading a set of 5 frames for a graphic and calling the data for frame 3 directly from the list.
Upon looking around at a couple potential posts that may be related, I found something that was related, and made me wonder. Is there even a built in function to GET the index of a recently added object?
The link I am looking at that made me think of this was: ArrayList indexOf() returns wrong index?
Basically, the way I was looking at it was that I would do something along the lines of the following psuedocode:
private ArrayList<FrameData> mylistofframeshere = new ArrayList();
FrameData Framenumberone = new FrameData(constructorblah goes in here);
int wherediditgo = mylistofframeshere.add(Framenumberone);
Or I thought I could do something along the lines of
mylistofframeshere.getindex(Framenumberone);
My backgrounds in coding are more procedural based at this point, so I am more used to knowing what the index is, just in order to place the data to begin with. I looked around at the oracle documentation as well, with findings something similar to the above link. Any suggestions??
EDIT : I'm going to add some extra clarification in here, because I really didn't put enough effort into the example and explanation.
Another example of trying to use something like a direct index of a list would be if I had a set of tiles I wanted to use as terrain for a game or something. I would load a set of possible tiles for the area into a central ArrayList. Upon trying to place these tiles, I would just reference the pre-loaded object I have in my ArrayList in order to draw the appropriate bitmap/whatever.
I'm still a bit new to Java, so I'm willing to bet it's just something simple I'm overlooking in the mechanics of using these datatypes. I'll keep editing this until I get the explanation right.
When you add something to an ArrayList, it goes to the last available space. In other words:
List<FrameData> list = new ArrayList<FrameData>();
list.add(frame1);
FrameData frame = list.get(list.size() - 1); //frame == frame1
But I wonder why you would need to do that. If you explain more about what you are trying to achieve, there might be a different / better way to get to the same result.
There is a method like ArrayList.indexOf(object); , Try using that method to get index of the object
It all depends on what you want to use the index for. If you simply need to map each element in your list to a key so you can later retrieve the element with the key, you should perhaps consider using a HashMap. If you are more concerned with the ordering, you can use a List. As someone already answered, the index with be incremented as you add elements into the list. If you know the total number of frames you will have before hand, you can initialize an ArrayList by passing in the size as an argument to its constructor, then add each frame by manually specifying the index with list.add(0...size-1, element).
In short,
If you simply want to store and retrieve by your own key /
incremented key -> use a HashMap.
If ordering is important, use a list.
Instead of using ArrayList in this way, you can use a Map<Integer,FrameData>. you can replace Integer with anything which might fit better in your project.

Adding all wrong answers into an array with Java - how?

I want to take all the questions that were answered incorrectly (it's a simple program asking math questions) and if they got the question wrong, add the question number to the array for further use.
But, I don't know how long this array will be, it could theoretically be of a different length each time the program is ran. So how would I set up the array?
You should use an ArrayList instead.
You could do something like:
ArrayList<String> wrongAnswers = new ArrayList<String>();
// Call this function with the user's answer as a parameter, when the answer
// has been determined to be incorrect.
public void wrongAnswer(String answer) {
wrongAnswers.add(answer);
}
public void printWrongAnswers() {
System.out.println("Wrong answers:");
for (String answer : wrongAnswers) {
System.out.println(answer);
}
}
Start with an ArrayList and then you can call toArray() to get an actual array.
You can also initialize an array whose size is the number of questions you have. Then keep a running count of missed questions, and simply trim the array at the end.
Look into using an ArrayList. This is an implementation of the List interface that is backed by an array.
Using the default constructor, it will start with a backing array of size 10 (but don't worry too much about this detail):
List<Question> questionList = new ArrayList<Question>();
You can then add elements:
questionList.add(question);
It will then resize this array as needed as you continue to add elements.
Since you probably know how many questions you are going to ask, you can stick to the array if you like and make it exactly as long as the number of questions you have. I would like to see the first person who succeeds in answering more questions incorrect then the number of questions available on the test
Use a collection, like a List implementation (like ArrayList), instead of an array. Then you can add by calling list.add(miss) and never worry about the size.
Do you specifically need an array? You can get the array, but in general, it's rare to specifically need one for requirements like these.

How do I create an array of strings without specifying its length in the beginning?

I want to create an array of strings, but I do not know the length of it in the beginning. It's like the array length depends on many factors and it's only decided when I fill strings/words into it. however, processing does not allow me to do that, it asks me to specify the length in the beginning. How can I get rid of this?..Thanks for all help. Any suggestion will be appreciated.
Amrita
List<String> strs = new ArrayList<String>();
strs.add("String 1");
strs.add("String 2");
strs.add("String 3");
System.out.println(strs.size()); //3
System.out.println(strs.get(1)); //String 2
Something like that is all you need! You don't need to worry about resizing, copying stuff in memory or whatever - the list will just expand as it needs to. All of the performance details are taken care of and unless you're really interested in how it works, you don't need to read about those details to use it.
You can use ArrayList: http://processing.org/reference/ArrayList.html
I would start by using ArrayList and resizing it when necessary. Java pre-allocates memory for ArrayList so that not every resize means that the contents are copied in memory. Access to ArrayList is faster than to LinkedList (it's O(1) instead of O(n)). Only if you find that the resizing of the ArrayList takes too much time, would I think of switching to LinkedList.
Use the typed ArrayList as #berry120 suggests (otherwise, you'll need to cast from Object to String all the time).
Also, if it helps, Processing has some functions for handling Arrays (like append() and expand()). Look under Array Functions in the Processing reference.
Behind the scenes the above mentioned Array Functions use System.arraycopy(), if that's of any use.
You need to use a LinkedList structure: this gives you an easily expanded container array and takes an initial capacity in the constructor, rather than a set limit. This will also be more efficient than an ArrayList, which will copy it's contents every time you exceed the current capacity, rather than simply add to it.

Categories