Java - A loop in a loop and the format gets lost - java

I'm French so excuse my English not necessarily correct.
I explain the context, I currently have a String array list named "tempCustomerDrugsIdsList" (var1) and another string array list named "tempDrugsTableList"(var2).
When I make a loop "For" on "var1" then another one in "var2","var2" loses its format, i. e. upper case is replaced by lower case and spaces are deleted.
I tested with another loop with the same type of variables (but empty), the result being the same I think the problem comes from my way of using java. Being on vb. net before, I must have taken some bad habits !
I don't know how to solve this problem, I've only been working in java for 2 weeks.
Thank you for helping me.
[EDIT]
My problem was:
List<String[]> tempDrugsTableList = otherList;
But this code doesn't duplicate the list.
AxelH gave me the following solution:
List<String[]> tempDrugsTableList = new ArrayList<String[]>(otherList);

Well, you are not doing a "copy" of the list
tempDrugsTableListCopy = tempDrugsTableList; // Get copy of original tempDrugsTableList for comparate
but sharing the reference, every update done in the tempDrugsTableListCopy will be done in the original list (same reference, same adress in memory). Since you are updating that copy in the following loops ... you update the original list too. What you want is to clone the list.
You could do it simply with copyList = new ArrayList(originalList); or for a deep clone, you need to iterate each element to duplicate those. (array need to be duplicated too if you change the value in those)

"String[]" tmpCustomerIds means you are getting a string array from a string array, which you would be using in a 2d array. Try it with just "String" in the for each loops. I am assuming you are using 1d arrays in this case.

Related

Way to save vectors in a list

I have a problem with the TSP algorithm
. I'm going to insert code and explain:
List listOfPermutations = new ArrayList();
while (cont.compareTo(deleteRutes) < 0) {
listOfPermutations.add(indexOfCities);
nextPermutation(indexOfCities);
....
The problem I have is the following,
my idea was to insert all possible permutations (arrays) in a list, but the problem is that the list always takes the same values ​​of the array, it is logical since the indexOfCities array is only one. I've been giving it back for a while and I do not know how to solve it. Can someone help me?
indexOfCities holds a reference to an array. This same reference is added as item to listOfPermutations with
listOfPermutations.add(indexOfCities);
in each loop iteration.
Then the array is modified with
nextPermutation(indexOfCities);
in each loop iteration. So the stored references all point to the same modified array.
To solve this, add a copy of the array in indexOfCities to listOfPermutations instead. E.g. like so:
int[] indexOfCitiesAux = indexOfCities.clone();
listOfPermutations.add(indexOfCitiesAux);

How to call Collections.Shuffle on only part of an array Java

So I have the following array:
String [] randomList = new String [16];
randomList[0]="Dog";
randomList[1]="Dog";
randomList[2]="Cat";
randomList[3]="Cat";
randomList[4]="Mouse";
randomList[5]="Mouse";
randomList[6]="Car";
randomList[7]="Car";
randomList[8]="Phone";
randomList[9]="Phone";
randomList[10]="Game";
randomList[11]="Game";
randomList[12]="Computer";
randomList[13]="Computer";
randomList[14]="Toy";
randomList[15]="Toy";
I want to shuffle only the first 9 elements of this array. I used the following code but it shuffles the entire array.
Collections.shuffle(Arrays.asList(randomList));
How would I shuffle only a part of the array rather than the whole thing? I am making quite a simple program so I would like to keep using the Collections class however all solutions are welcome. Thanks
You can use the List type's subList method to get a List object with a view of a particular range of elements from the original list. I haven't tested this, but I think it should work:
Collections.shuffle(Arrays.asList(randomList).subList(startIndex, endIndex));
You can also try the below. However, more cleaner code would be as suggested by templatetypedef. List<String> newList = new ArrayList<String>();
for(int i=0; i<randomList.size()-ValuePreferred; i++){
newList.add(randomList.get(i));
}
Collections.shuffle(newList);
randomList.removeAll(newList);
newList.addAll(randomList);
Also, i hear about memory leak issue with Sublist in arrays. Not sure if that got rectified. If someone can provide any useful information regarding that would be great. Remember specifically calling value in between the List will cause IndexOutOfBoundsIssue(). That should be handled.

Re initialize a string array with no more memory left

In Java, since strings are immutable, when we re assign a string Array element to a different string and are out of memory would it compile and run fine?
my understanding is for example if there are 2 elements in a string array, "John" and "Henry", when i change the array's second element to "Tom", what happens to "Henry" since it cant be really over written (immutable strings) and behind the scenes is java pointing to a new location (should array locations not be next to each other? ).
I ran a test and it successfully changed the second element to Tom. It compiled and ran fine. As per my understanding this should not have been allowed because strings cant be over written and array are supposed to be consecutive memory locations. please clarify - thanks
Each cell of your array contains the address of a String instance. When you change the value of the second cell it just points to another String instance, and if the instance previously pointed by that cell is no longer pointed by any other variable, might be chosen for garbage collection.

Which Array / List should I use to keep an static index?

I usually use HashMap<Integer, Object> to keep an array of objects where you can get items by Integer.
I'm showing you an example so you can understand.
HashMap<Integer,String>:
[0] - Hello
1 - How are you doing
[2] - Bye
So with a HashMap, I can remove items avoiding the rest moving from their indexes.
hashmap.remove(0)
[0] - null
1 - How are you doing
[2] - Bye
But HashMap shouldn't be used for indexes with an Integer. So... Which kind of array should I use to perform actions like the ones I am explaining above?
Edit: About the part of "shouldn't be used", this is what Android Eclipse is telling me:
You can use a simple Array. They can be pointed by integer. And other than calling remove you can set null to the specific place. If you really want to call remove write your own wrapper method which does that for you.
I your indices are dense (no big holes in a range [0..n], the most efficient approach would be to use a plain array of String:
final String[] lup = new String[3];
lup[0] = "Hello";
lup[1] = "How are you doing";
lup[2] = "Bye";
// to remove elements just set the index to `null`:
lup[0] = null;
You can use SparseArray which is similar to HashMap<Integer,String>
SparseArray<String> arr=new SparseArray<String>();
arr.put(0, "Hello");
If you already know the total size, then go with Arrays. But if you don't then go with ArrayList.
Now, I don't see a purpose of mapping here.
Hashmap is a Map data structure. Like a list each item that is stored in a hashmap is stored at a particular index. This index is called a hash and it is generated using a hash function. Hash functions accept the object to be stored as an argument and generate a number that is unique to it. Different hashing functions have different trade-offs. A function that is too sparse will use up more space than required(your case). while one that is not sparse enough will suffer from collisions where objects use the same hash.
Further Reading if interested: Look at Android's SparseArray implementation for inspiration.
View the source by downloading AOSP's source code here http://source.android.com/source/downloading.html.
It is highly optimized for integers!
Actually, you can use a simple array of strings.
String arr[] = new String[size];
After reading a little bit, I guess the answer is the following:
1.- I can't use plain arrays. Reason: I might not know the final size of it.
2.- Lists doesnt fit, as when you remove an item, the following items fits to the new index. I don't want index move.
So as a global answer, using HashMap is OK, however using SparseArray is recommended as it is more efficient.

How do I make an array from inputted information (i.e. names) and then use it as objects within the code?

I've been reading up on it, but every question I've found has asked for slightly different things, such as only wanting a single letter for their array, or in a different language (I'm new and only learning java at the moment), so here I am.
I want to set up an array that uses the user's input for their names.
What I have so far is this, I'm assuming this is the declaration line, where later I use an input line to define a value within the array (which I also am unsure how to do)
String[] array = {"name"};
But I don't know how to for example print.out the object or keep up with which name will be what value. I appreciate your time taken to teach me!
EDIT for further clarification. I'm trying to write up a small app that asks the user for numerous names, addresses, and phone numbers (Type name -> Type name's address -> type name's phone number, ask if they want to add another person, if yes then go back to asking for another name)
I am unsure how to set up a String array or how to use it throughout. However, thanks to your input and coming back after some fresh air, I have a better idea how to word it for google. Thank you guys for your help, even if it was just to gesture a better articulated question.
An array is a sequence of values. You have created an array of Strings that is one String long. To access the value at a specific of an array, use array subscript notation: the name of the array followed by a pair of square brackets ([]) with the index in between them.
String[] anArrayOfStrings = {"string0", "string1", "string2"};
anArrayOfStrings[0]; //the first element
System.out.println(anArrayOfStrings[1]); //print the second element
anArrayOfStrings[2] = "new string value"; //assign the third element to a new value
if (anArrayOfStrings[0].equals("string0") //evaluate the first element and call a method
{
//this block will execute anArrayOfStrings[0] is "string0"
}
anArrayOfStrings[3]; //error, index out of bounds
Simply declaring the array would be
String[] names;
In your code you both declare and assign it in the same line by using an initializer list.
To assign individual elements, use the [] notation. Note that once you initialized you list to be only one String long, it cannot become longer than without be re-assigned. To declare an array of any size, you can use:
String[] arrayWithInitialSize = new String[5]; //holds five strings, each null to begin with

Categories