Solving CodingBat sum28 and withoutTen with array lists - java

So I just finished some problems off of codingbat.com, sum 28 and withoutTen, and I wanted to know if there was a way to do them with array lists rather than just arrays. I am trying to get some practice with array lists before my next coding assignment.

So, if your question is "can I use array lists instead of the arrays on codingbat?", the answer is yes.
Just a couple of small points change.
With arrays, you'd use array.length to get the size. For arraylists, it is arraylist.size()
To access elements in an array, you use array[0]. For an arraylist, it is arrayList.get(0).
Finally, it initialize an array, you use int[] array = new int[10];. For an arraylist, you'd use ArrayList<Intenger> name = new ArrayList<Integer>();. You typically won't assign it a size. To add elements to it, use name.add(5).
Just make sure to add import java.util.ArrayList; at the top of your class so that you can actually access all of these methods.
I hope that helps. Good luck :)

Related

How to initialize an ArrayList with a certain size and directly access its elements

I was writing something that needs an arrayList of size n, so I did the following:
List<Set<Integer>> list = new ArrayList<Set<Integer>(n);
And when I was trying to access an element of the list e.g.
list.get(someValue that is <n)
I got arrayList out of bound exception, so I guess putting a n there doesn't really help you initialize the list, but just pre-allocate the space.
Is there a way to do the initialization after which there are actually null or objects in each slot?
I end up using a for loop and adding n empty set and then index into the list.
Is there a better way TO INITIALIZE AN ARRAYLIST IF THE SIZE IS KNOWN IN ADVANCE?
Please know what I'm asking before saying this is a duplicate.
Hope my question is clear.
Thanks in advance.
Some of you think what I tried to do is meaningless. This happens when I tried to solve a bucket sort related problem where the index of the set I tried to access in the array is known. So for example, I want to add some elements to the set at position 1, 3, 2, 4... then it would be convenient if I can just get the set at position 1, 3, 2, 4...
If you take a look at Java API documentation, you will see that there are 3 constructors provided for ArrayList:
ArrayList()
ArrayList(Collection c) - Constructs a list containing the elements of the specified collection, in the order they are returned by the collection's iterator.
ArrayList(int initialCapacity) - Constructs an empty list with the specified initial capacity.
You can use second of listed constructors if you need to fill ArrayList's slots in the place of its definition. You need to be aware that there needs to be passed a Collection, so you can do something like that, for example:
ArrayList<Integer> al = new ArrayList<>(Arrays.asList(1,2,3,4,5);
Now size() of al is 5 and it is filled with numbers 1,2,3,4 and 5.
Also, you need to be aware that ArrayList doesn't work like Arrays and it's size is not fixed - it changes due to adding or removing items.
I'm taking the liberty of repeating bcsb1001's solution, which is perhaps obscured by various comments. In order to initialize an array of a fixed size with valid placeholder values:
new ArrayList (Collections.nCopies (n, null));
This idea was the best I could find in various searches, maybe it will work for others too.

When to use ArrayList and when to use simple integer array

Can anyone please explain in which situation are we supposed to use ArrayList instead of a simple array and what is the difference between these two and how to initialize the ArrayList.
I am new to java so use example if possible.
Whenever you don't know the size to be created, you can use ArrayList.
If you just want speed access, you can use array (indexing in array is faster than ArrayList).
And also, ArrayList reduces the complexity of coding.
ArrayList can be initialized like this
ArrayList al = new ArrayList();
Add values to the ArrayList
al.add("String");
al.add(number);

Sort array and reflect the changes in another array

I have an array of doubles, in Java : arr1 which I want to sort. Most probably the first option would be the utility method Arrays.sort(double[]).
The idea is that I want the same changes (e.g. value at index i is interchanged with value at index j in arr1) to be reflected in another array of integers: arr2 (in the sense that the values at the same indexes are changed also in arr2).
Is there a simple way (a trick) to accomplish this in Java? Or the only way is to implement the sorting algorithm by myself?
UPDATE: I see that people recommend replacing the two arrays with one array of objects containing the 2 values (one from arr1 and one from arr2). Wouldn't this bring some efficiency penalties. In other words, isn't it less efficient to sort an array of objects than an array of primitive types (doubles in this case) ?
The data is completely static. It's large (it fits in memory) but static.
Rather than trying to maintain sorted parallel arrays, a cleaner solution would be to create a class that encapsulates both of your data values, and just have one array of objects.
(But to answer your question, there is no built-in way to do this in Java. Implementing your own sort routine that keeps two arrays sorted based on values in one of them would work for a small amount of data that isn't likely to change, but it would be difficult to maintain.)
One solution which is doesn't impact the performance of sorting, ie still O(nlog(n)) time complexity.
Use a map to store array[i] -> i
Sort the array
Iterate over the sorted array, and for each value, use it as a key for the map to retrieve the original index.
Edit: Raihan comment make me look miserable :(
Try it this way....
- Convert this array into ArrayList using the Arrays.asList()
- Create another List Object Reference Variable and assign the same ArrayList object to it, Now any changes to the first ArrayList will be reflected to the Second ArrayList.
Eg:
double[] array = new double[10];
ArrayList<Double> arList_1 = new ArrayList<Double>(Arrays.asList(array));
ArrayList<Double> arList_2 = arList2;
Now for sorting, there are 2 options:
- Use java.lang.Comparable Interface, if you want to sort it in only 1 way.
- Use java.util.Comparator Interface, if you want to sort it in more than 1 way.
Note sure what are you looking for but one other work around could be like this.
Create a map to maintain the relation between arr1 and arr2 elments
Map<Double, Double> myLocalMap<Double, Double>();
for(int ind=0; indx < arr1.length; indx++){
myLocalMap.put(Double.valueOf(arr1[indx]), Double.valueOf(arr2[indx]));
}
Now sort arr1 as you said:
Arrays.sort(arr1);
Once arr1 is sorted, update arr2 as below:
for(int ind=0; indx < arr1.length; indx++){
arr2[indx] = myLocalMap.get(arr1[indx]).doubleValue();
}

Is having a List and an array with the exact same element bad programming style?

I have a short (12 elements) LinkedList of short strings (7 characters each).
I need to search through this list both by index and by content (i.e. search a particular string and get its index in the list).
I thought about making a copy of the LinkedList as an array at runtime (just once, since the LinkedList is a static member of my class), so I can access the strings by index more quickly.
Given that the LinkedList is never changed at runtime, is this bad programming practice or is this an idea worth considering?
IMPORTANT EDIT: the array can't be sorted, I need it to map specific strings to specific numbers.
Instead of a LinkedList just use an ArrayList - you can look up fast based on an index, and you can easily search through it.
What problem are you trying to solve here? Are you worried that accessing elements by index is too slow in LinkedList? If so, you might want to use ArrayList instead.
But for a 12-element list, the improvement probably won't make any measurable difference. Unless this is something you're accessing several hundred times a second, I wouldn't waste any time on trying to optimize it.
Another idea you might want to consider is using a Map:
Map someMap<int, String>
It's easy to search for values in a map by both key and value.
Might also not be the best idea, but at least better then creating 2 lists with the same values =)
The question is, why are you using a LinkedList in the first place?
The main reason to choose a LinkedList over an array list is if you need to make a number of insertions/deletions in the middle of the List or if you don't know the exact size of the list and don't want to make a number of reallocations of the Array.
The main reason to choose an ArrayList over a LinkedList is if you need to have random access to each of the elements.
(There are other advantages/disadvantages to each, but those are probably the main ones that come to mind)
It looks like you do need random access to the list, so why did you pick a LinkedList over an ArrayList
I would say it depends on your intention and the effect it really has.
With only 12 elements it seems unlikely to me that converting the LinkedList to an array has an impact on performance. So it could make the code unnecessarily (slightly) harder to understand for other people. From this point of view it could be considered a non optimal programming style.
If the number of elements increases, i.g. you're need to pre-process some data which would require a dynamic data structure. And for later use an indexed lookup performs much better, this wouldn't be a bad programming style, rather a required improvement.
Given that you know the exact amount of elements you are going to be using why not use an array from the start?
string[] myArray = new string[7];
// Add your data
Sort(myArray); // Sort your strings
int value = binarySearch(myArray, "key"); // Search your array
Or since you cant sort the array you could just make a linear search method
public int Search(string[] array, string key)
{
for(int i = 0; i < array.legnth(); i++)
{
if(array[i] == key)
return i;
}
return -1;
}
Edit: After re-loading the page and reading peoples responses I agree that ArrayList should be exactly what you need.

Using Collections API to Shuffle

I am getting very frustrated because I cannot seem to figure out why Collections shuffling is not working properly.
Lets say that I am trying to shuffle the randomizer array.
int[] randomizer = new int[] {200,300,212,111,6,2332};
Collections.shuffle(Arrays.asList(randomizer));
For some reason the elements stay sorted exactly the same whether or not I call the shuffle method. Any ideas?
Arrays.asList cannot be used with arrays of primitives. Use this instead:
Integer[] randomizer = new Integer[] {200,300,212,111,6,2332};
Collections.shuffle(Arrays.asList(randomizer));
The same rule applies to most classes in the collections framework, in that you can't use primitive types.
The original code (with int[]) compiled fine, but did not work as intended, because of the behaviour of the variadic method asList: it just makes a one-element list, with the int array as its only member.
Chris' answer is correct.
As i said in a comment on Chris' answer, your underlying array will change appropriately unless the arraylist needs to grow, and the list creates a new one and copies items into it.
You may want to keep a reference to the list and iterate over that after the Arrays.asList call, and not iterate over the array after that, iterate over the List instead.

Categories

Resources