Keeping Information from previous variables and outputs - java

Making a small program where I enter Word/s and it hashcodes turning it into numbers so I can use these numbers for the likes of seeds for games such as Rimworld or Minecraft.
What I currently use is:
String levelSeed= "hello";
int levelSeedNum = levelSeed.hashCode();
System.out.println(levelSeed);
Which works nicely. But I have been thinking about holding the Word/s and what the hashcode is in a List so I can see what I have already used. I cant seem to figure out how to do this as when I add a new Word/s it resets the list I have.
ArrayList<String> ls = new ArrayList<String>();
ls.add(levelSeed);
System.out.println(ls);
What would be the best way to not have the list reset every time I execute the code?

Your problem seems to be that you're assigning ls to a new list every time you have a new seed:
ArrayList<String> ls = new ArrayList<String>();
This means that you lose whatever was in the old list. What you need to do is simply to initialize that list only once, and then add multiple elements to it:
ArrayList<String> ls = new ArrayList<String>(); //this creates a new, empty list
//... do stuff
ls.add(aSeed);
//... do stuff
ls.add(anotherSeed);
//ls now has two elements in it
ls = new ArrayList<String>();
//and now it's empty
EDIT
If your want to build the list seed by seed, you'll need to do it in some sort of loop. Here's a simple example:
final int NUM_SEEDS = ...;
for (int i = 0; i < NUM_SEEDS; i++) {
String seed = ... //collect a seed by whatever means you're using
lst.add(seed);
}
//lst.size() is now NUM_SEEDS.

Related

wanted put array list items into variables using loop

i am dynamically adding items to array-list after i wanted to
Initialize Variables using this array-list items
my array-list is
ArrayList<String> dayCountList = new ArrayList<String>();
i try to do like this but it doesn't work
for (int i = 0; i < dayCountList.size() ;i++) {
double day+"i" = Double.parseDouble(dayCountList.get(i));
}
You can create a array or array list of double type like this.
ArrayList<String> dayCountList = new ArrayList<String>();
.
.
double day[]=new double[dayCountList.size()];
// now use your loop like this
for (int i = 0; i < dayCountList.size() ; i++) {
day[i] = Double.parseDouble(dayCountList.get(i));
}
Now you can call your variables like day[0], for first element
day[1] ,for second and so on.
Hope this helped you.
If you are doing this, then you probably did not understand the purpose of array lists is. One purpose of array list is exactly to avoid creating a whole bunch of variables named day1, day2, day3 and so on.
You seem like you want to transform every element in the array list to a doubles. Why not create another ArrayList<Double> or double[] to store the transformed elements? Instead of writing day1, day2, you can say days.get(0), days.get(1) in the case of array lists. With arrays, you can do days[0], days[1] and so on.
ArrayList<Double> days = dayCountList.stream()
.mapToDouble(Double::parseDouble)
.boxed()
.collect(Collectors.toList());
// or
double[] days = dayCountList.stream()
.mapToDouble(Double::parseDouble).toArray()

Java Arraylist and Map

I don't have idea how to search this:
Random generator = new Random();
Map<Integer, ArrayList> mapOfprevOp = new HashMap<>();
ArrayList<Integer> listPrev = new ArrayList<>();
listPrev = mapOfprevOp.get(operacja);
System.out.println(listPrev); // it will show []
int rnd = generator.nextInt(op_cnt) + 1;
listPrev.add(rnd);
System.out.println(mapOfprevOp.get(operacja)); // it will show value of listPrev
Why second System.out print me on the screen value of listPrev?
It shouldn't still print [] ?
listPrev = mapOfprevOp.get(operacja);
This line works different than i could expect?
This would suggest that at your first System.out.println invocation the list is empty.
If you look here https://docs.oracle.com/javase/7/docs/api/java/util/AbstractCollection.html#toString%28%29. We can see that the toString method for a list returns the elements between square brackets. Thus [] is an empty list.
At the second call you have added an element which is why you see it. You need to bare in mind that in Java we pass objects by reference meaning that your listPrev references the SAME LIST as the one contained in the map.
If you want to just get the value, then I would suggest you change
listPrev = mapOfprevOp.get(operacja);
to be
listPrev.addAll(mapOfprevOp.get(operacja));
This will add all of the elements from mapOfprevOp.get(operacja) to listPrev without subsequent operations affecting the map which seems to be what you want.
Also, Map<Integer, ArrayList> mapOfprevOp = new HashMap<>(); Generally it is better to use interface types in delcarations like you have with Map. So I would consider switching ArrayList to be List.
The object that you use its self can still be an ArrayList, like this:
Map mapOfprevOp = new HashMap<>();
List listPrev = new ArrayList<>();
This means that if you wanted to change it to be a LinkedList, you would only change it in one place rather than 3. Note that with the exception of Arrays.asList lists all lists can be resized.

How to "propagate" the sorting of an `ArrayList<String>` to another one?

I have multiple ArrayList<String>s "linked" into a custom adapter I'm using to build a list view.
Now suppose they are just two in total, to simplify.
I want to sort one of them and then have this new order reflected into the other one, in order to maintain the list consistent.
This is what I was thinking to do and doesn't work, ending with an IndexOutOfBoundsException: Invalid index 0, size is 0 at the line signed with *.
// initial declarations:
List<String> filenameEntries = new ArrayList<String>();
List<String> idEntries = new ArrayList<String>();
/* various operations that fill
the two ArrayList here... */
// sorting:
List<String> oldFilenameEntries = new ArrayList<String>();
List<String> oldIdEntries = new ArrayList<String>();
oldFilenameEntries = filenameEntries;
oldIdEntries = idEntries;
idEntries.clear();
Collections.sort(filenameEntries);
for (int i = 0; i < filenameEntries.size(); i++ ) {
for (int j = 0; j < oldFilenameEntries.size(); j++ ) {
if (oldFilenameEntries.get(j) == filenameEntries.get(i)) {
idEntries.add(oldIdEntries.get(j)); // *
}
}
}
My idea was to search into the old ArrayList for every element from the new one, and then use this "old" index to re-polulate the other ArrayList.
(I have the restriction that the other "sorted" ArrayList must be again idEntries. This is way I did this sort of transfer)
Any suggestion?
Thanks.
EDIT:
I thought it was a sorting issue and then came out I missed the right way to make a copy for the ArrayLists. Thanks to everyone that pointed out that the error was at
oldFilenameEntries = filenameEntries;
oldIdEntries = idEntries;
and why.
I accepted the answer that pointed me more quickly to the solution.
I removed the two lines above and changed the previous into
List<String> oldFilenameEntries = new ArrayList<String>(filenameEntries);
List<String> oldIdEntries = new ArrayList<String>(idEntries);
and from what I can see ATM all seems to work as expected.
The issue is the assignment: oldIdEntries = idEntries; this is causing both references to point to same list so when you do idEntries.clear(); you have cleared the one list to which both are pointing. You need to make a copy of the list not just assign the reference.
Collections.copy
Lists.copy
ImmutableList.copy()
The problem is in these 2 lines:
oldFilenameEntries = filenameEntries;
oldIdEntries = idEntries;
After this, both old... and original variables point to the same list. Then you call idEntries.clear(). This clears both idEntries and oldIdEntries since they point to the same list.
For this to work, you need to copy the list instead of just assigning it. You could use Collections.copy(). Here is an example:
Java Collections copy list - I don't understand
On a different note, this approach seems too complex - but it's also not very clear what you are trying to accomplish so I can't suggest a better way.
Iterate over the soreted list, clone each object and then add it to the new array list
Two issues:
One:
oldFilenameEntries = filenameEntries;
oldIdEntries = idEntries;
Now, both old and new entries point to the same list.
Then, idEntries.clear().
This clears both old and new entries.
If you want to do this somehow, use Collections.copy()
Two:
If you're just going to check for equality, I don't see why you need to have two for-loops, and have both sorted.
You could just do this:
for (int i = 0; i < filenameEntries.size(); i++ ) {
if (oldFilenameEntries.contains(filenameEntries.get(i)) {
idEntries.add(oldIdEntries.get(j)); // *
}
}
}
NOTE: as I don't know what the original point of your code was, and equality checking was all I could infer from your snippet, I'm suggesting this.

How to replace one arraylist to another with different size in java

I have two array list with different size. How to Replace from this:
ArrayList<String> s = new ArrayList<String>();
ArrayList<String> f = new ArrayList<String>();
s.add("Nepal");
s.add("Korea");
s.add("Sri Lanka");
s.add("India");
s.add("Pakistan");
s.add("China");
s.add("Australia");
s.add("Bhutan");
f.add("London");
f.add("New York");
f.add("Mumbai");
f.add("sydeny");
for(int i=0;i<s.size();i++){
// Collections.copy(f, s);
f.addAll(s);
Log.d("TAG", "Sources---" + s.get(i));
Log.d("TAG", "Dest---" + f.get(i));
}
I have try both this. but not replace only append or copy from the existing array list.
My aim is totally replace original array to new arraylist.
You may do clear() first and then do addAll(s);
After clear() your arraylist will be empty.
EDIT:
As #Luggi commented, clear() will not be good option if list is big, instead simply point your f reference to new ArrayList with collection as parameter:
Example:
f = new ArrayList(s);
enter link description hereenter link description hereYou can do this in many ways
First clear then add all
f.clear();
f.addAll(S);
By first way all element copy from one list to another list if you want that both the list are same and manipulation in one list reflects in another list then you can point both on the same list like
f = s;
By intializing new list by adding all element into a new list.
f = new ArrayList(s);
ArrayList<String> s = new ArrayList<String>();
ArrayList<String> f = new ArrayList<String>();
s.add("Nepal");
s.add("Korea");
s.add("Sri Lanka");
s.add("India");
s.add("Pakistan");
s.add("China");
s.add("Australia");
s.add("Bhutan");
f.add("London");
f.add("New York");
f.add("Mumbai");
f.add("sydeny");
f.clear();
f.addAll(s);
If you want to add elements in f to s following will work
s.addAll(f);
That's all. Why you use for loop in your code?
You can try this out:
First add all elements from s to f
f.addAll(s);
Then retain only elements in f that are present in s
f.retainAll(s);

For Loop doesnt add point to an array

I have the following for loop which looks through a string ArrayList of results, each item in the string is seperated by "::":
ArrayList<String> resultsArray = MyClass.results;
Integer numPoints = resultsArray.size();
for (int i =0;i<numPoints;i++){
String[] pointDetails = resultsArray.get(i).split("::");
String pointName = pointDetails[0];
String pointDescription = pointDetails[1];
String coordinates = pointDetails[2];
//Turn coordinates into geopoints
String coord[] = coords.split(",");
Integer lng= (int) (Double.valueOf(coord[0]) * 1000000);
Integer lat = (int)(Double.valueOf(coord[1])*1000000);
GeoPoint gPoint = new GeoPoint(lng,lat);
arrayPointName = new ArrayList <String>();
arrayPointDescription = new ArrayList <String>();
arrayPointCoords=new ArrayList<GeoPoint>();
arrayPointName.add(pointName);
arrayPointDescription.add(pointDescription);
arrayPointCoords.add(gPoint);
}
I know I have 20 points in the initial string ArrayList and have printed out its size to check this. However, when I print out the new arraylists, such as arrayPointName, they only contain one point. Any idea on why this is?
Look at this code:
arrayPointName = new ArrayList <String>();
arrayPointDescription = new ArrayList <String>();
arrayPointCoords=new ArrayList<GeoPoint>();
Those three statements - assigning new, empty ArrayList references to your variables - are being executed on every iteration of your loop.
They should come before your loop instead: you only want to initialize the variables once (creating the three lists) and then add a new item on each iteration.
As a side note, populating multiple collections like this is normally a bad idea. It's usually better to create a single type which encapsulates the related data (name, description, coordinates in this case) and then create a single collection of items of that type. That's usually a lot easier to work with.
you used coords as an ArrayList Without initiate it .Also you initiate for each iteration arrayPointName, arrayPointDescription and arrayPointCoords that's why they lost the value created in the previous iteration. they should be initiate juste one time before starting the loop
it will be easy to help you if you give us a sample of resultsArray strring.

Categories