Hello im rather stuck on this part of my java programming work. I have done what i think is right for this question but im unsure if it is right as the next question asks to add 4 different strings into two different sub-lists (and thats where im getting stuk).
This is the first question:
Create a variable called balancedThings of type ArrayList of ArrayLists of Strings and add a method balancedInit() that instantiates the balancedThings variable by creating a new ArrayList > object and that also creates two new ArrayList objects and adds these to the balancedThings list.
this is the second question:
Add a method balancedCreation() that adds the strings “sword” and “map” to the first of the two sub-lists, and the strings “shield” and “bottle” to the second sub-list.
This is my answer:
void balancedInit()
{
balancedThings = new ArrayList<>();
balancedThings.add(0, "SubListOne");
balancedThings.add(1, "SubListTwo");
}
Can anyone explain if this is right for the question and where i should go next in order to add into sublists?
I think you just need to build the solution from the bottom up. Before worrying about the list of lists, worry about the individual lists first.
So first, you just want a list of strings. You can do that like this:
private static ArrayList<String> firstSublist() {
ArrayList<String> list = new ArrayList<>();
list.add("sword");
list.add("map");
return list;
}
ArrayList is your list, and the String in angle brackets tells you what type is going to be in the list. Then you add the actual strings. Do this for the other sublist too.
Then when you have a way to make your little lists, time to compose the big one:
private static void balancedCreation(ArrayList<ArrayList<String>> listOfLists) {
listOfLists.add((firstSublist()));
listOfLists.add((secondSublist()));
}
Here you have a list of lists. I know all the angle brackets can be confusing with something like ArrayList<ArrayList<String>>, but just remember to look at it a little at a time from the inside out.
So with the big list, you are just adding a thing--exactly like the sublists. As long as you take care of business at the simpler level, building up to the top level is no sweat.
In the end, main looks like this
public static void main(String[] args) {
ArrayList<ArrayList<String>> listOfLists = new ArrayList<>();
balancedCreation(listOfLists);
}
Hope this helps.
you want to add an ArrayList of Strings in an ArrayList :
public void balancedInit() {
ArrayList<ArrayList<String>> balancedThings = new ArrayList<ArrayList<String>>();
ArrayList<String> subListOne = new ArrayList<String>();
ArrayList<String> subListTwo = new ArrayList<String>();
// add values to your Sub Lists then ...
balancedThings.add(subListOne); // this will be index 0 implicitly
balancedThings.add(subListTwo); // this will be index 1 implicitly
}
programmers prefer using polymorphism in Collections framework, like declaring the ArrayList as List, but this is not a good practice when it comes to Serialization
initialize andinstantiate the "SublistOne" and "SubListTwo" in the way you initialized the BalancedThings.
that should create the sublist.
void balancedInit()
{
ArrayList<ArrayList<String>> balancedThings = new ArrayList<ArrayList<String>>();
ArrayList<String> subLiostOne = = new ArrayList<String>();
ArrayList<String> subLiostTwo = = new ArrayList<String>();
subListOne.add(0,"sword");
subListOne.add(1,"map");
subListTwo.add(0,"shield");
subListTwo.add(1,"bottle");
balancedThings.add(0, subListOne);
balancedThings.add(1, subListTwo);
}
please mark the answer as helpful if it is helpful
Related
Im working on a coin sorter project. At the moment I'm trying to create a method that takes two values (total value, and a type of coin), and will return the total value sorted out into all the coin denominations EXCEPT the type of coin.
For example multiCoinCalculator(562, 50) would return "2x200p, 1x100p, 0x50p, 3x20p, 0x10p with a remainder of 2p".
I have a pretty good idea of how to do this but I am struggling to remove a value the "type of coin" value from my array.
//multiCoinCalculator method
public String multiCoinCalculator(int totalValExchange, int coinType) {
int[] list= {10,20,50,100,200};
list = ArrayUtils.removeElement(list, coinType);
return list;
}
Here you can see what I am trying to do so far. I am just wanting to remove the coin type (would be 50 with the example), from my list. I have been fiddling with it for ages but cant seem to get it to work at all!
The errors that come up are "ArrayUtils cannot be resolved" and "type mismatch: cannot convert from int[] to String"
Any ideas? Would be greatly appreciated!
You are using an array here which is a fixed-size data structure where you can't remove an element from it, you need an array list here, try this,
ArrayList<Integer> list new ArrayList<>();
list.add(10);
list.add(20);
list.add(50);
list.add(100);
list.add(200);
// then remove it by using an index
list.remove(2); // this will remove 3rd element.
First of all, you should call the ArrayList as follows.
public static void main(String[] args) {
List<Integer> coins= new ArrayList<>();
coins.add(10);
coins.add(20);
coins.add(50);
coins.add(100);
coins.add(200);
List<Integer> result = multiCoinCalculator(coins,520,50); }
You should pay attention to this when calling the method to keep the answer in an ArrayList.
List<Integer> result = multiCoinCalculator(coins,520,50);
Accordingly, you can define a function like this.
public static List<Integer> multiCoinCalculator(List<Integer> c, int totalValExchange,int coinType) {
c.remove(coinType);}
/*In the meantime, I think the procedures to be done are the main point of this work, which is given as homework. */
return List<Integer> result; // if you want keep result via using ArrayList return must be an ArrayList}
You can make your new calculations with the new list you will create.
You can take a look at the Greedy Algorithm to solve your problem.
I have three ArrayLists:
One is used for storing user input in the order they were entered, located in the main class.
Second one is exactly the same as the first one, but it is passed into a method called remTrip to be copied and will return the result.
Third one is list1 in the code below, which is the one being processed.
public static ArrayList<String> remTrip( ArrayList<String> a){
//code here
ArrayList<String> list1 = a;
Collections.sort(list1);
//code to remove triplicates from the list and returns the result
}
I wanted to keep the first ArrayList<String> in the same order it was (i.e. {"dog", "cat" , "tiger", "cat", "cat"} ), but apparently the Collections.sort() sorts all of the ArrayLists.
How do I sort only one of the list and not the others?
The problem is not how Collections.sort() works. The problem is that instead of creating a copy of your list, you set the new list equal to your list. This means that they both point to the same object, sorting one will sort the other because they are the same thing. To solve this set list1 to a copy of a instead of setting them equal.
You should be able to do
ArrayList<String> list1 = new ArrayList<String>(a);
Three arralists you're talking about are not 3 different arraylists. They're just three different references to the same arraylist.
What you're doing essentially is -
List list01 = new ArrayList();
List list02 = list01;
List list03 = list01;
What you want is -
List list01 = new ArrayList();
List list02 = new ArrayList(list01);
List list03 = new ArrayList(list01);
But you should remember, this way will give you a copy of your List, not all it's elements. So, if you change one of the elements in your copied List, it will be changed in your original List too.
How to solve it - Hint copy constructor.
I've been having trouble with the next thing: I have an arraylist with numbers in it, and I want to reverse the numbers in the list, as in, if it had 1 2 3, replace the values in the arraylist with 3 2 1. To that end, I created a method called reordenar(); which puts the last number in the first arraylist in the first spot in the second arraylist. After this is done, I don't know how to make the first arraylist get its numbers replaced by the second. Here's the code I've written.
package firstPackage;
import java.util.*;
public class firstMain {
public static Object reordenar(List n){
List secondList = new ArrayList();
for (int i=0; i<n.size(); i++){
secondList.add(n.size()-i);
}
return n;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
List firstList = new ArrayList();
firstList.add("1");
firstList.add("2");
firstList.add("3");
firstList.add("7");
firstList.add("5");
firstList.add("6");
firstList.add("9");
reordenar(firstList);
System.out.println(firstList);
}
}
that code just prints out the normal order, not the rearranged one. thanks a lot for the help.
You don't need 2 ArrayLists to make this work. Just iterate upto half the elements of your ArrayList and use a temporary variable to exchange places between the 1st and the last, the second and the second form the end etc.
Also it's not a good idea to use ArrayList without giving the specific type it will contain like:
List<String> firstList = new ArrayList<String>();
The former (without the specific type) implies Object for your ArrayList which usually is too wide to be useful.
I'm running the following code, but getting error The method trimToSize() is undefined for the type List<Integer>
public class ListPerformance {
public static void main(String args[]) {
List<Integer> array = new ArrayList<Integer>();
List<Integer> linked = new LinkedList<Integer>();
//Initialize array with random elements in the first 50 positions, do other operations
addElement(array,"beginning");
//Resize to 100
for(int a=100;a<array.size();a++) {
array.remove(a);
}
linked.trimToSize();
}
...
I thought I did everything correctly as shown at this tutorial on ArrayList.trimToSize(). Why can't I use .trimToSize() here?
EDIT2: So thanks to the posters/commenters, I now know that my mistake was creating with element of List instead of ArrayList. But what about custom methods? Should I take those as arraylist/linked list or regular ol' List? What is considered "good-practice"? Or does that also depend on whether or not I need to use ArrayList-specific methods?
Thanks again!
trimToSize() is a method of the ArrayList class, not the List interface. Since you're storing your variables as List<Integer>, you can only use methods that are part of the List interface.
Change your variable declarations to:
ArrayList<Integer> array = new ArrayList<Integer>();
LinkedList<Integer> linked = new LinkedList<Integer>();
And you should be fine in your main, so long as you only try and trim array. You can't trim linked at all, because it's nonsensical to trim a LinkedList; they do not allocate additional buffer space past their capacity as appending to a LinkedList is always O(1), where as appending to a full ArrayList is O(n).
trimToSize() is a method of ArrayList but not of List. Not all Lists can be trimmed (e.g.: LinkedList)
List<Integer> linked = new LinkedList<Integer>();
linked.trimToSize();
You're calling it on the LinkedList. If you want to call it on the ArrayList use
ArrayList<Integer> array = new ArrayList<Integer>();
instead of the first line. (tell your compiler it's not any List, but an ArrayList)
Guys i wanna ask about the best way to iterate collection classes ??
private ArrayList<String> no = new ArrayList<String>();
private ArrayList<String> code = new ArrayList<String>();
private ArrayList<String> name = new ArrayList<String>();
private ArrayList<String> colour = new ArrayList<String>();
private ArrayList<String> size = new ArrayList<String>();
// method for finding specific value inside ArrayList, if match then delete that element
void deleteSomeRows(Collection<String> column, String valueToDelete) {
Iterator <String> iterator = column.iterator();
do{
if (iterator.next()==valueToDelete){
iterator.remove();
}
}while(iterator.hasNext());
}
deleteSomeRows(no, "value" );
deleteSomeRows(code, "value" );
deleteSomeRows(name , "value");
deleteSomeRows(colour ,"value" );
deleteSomeRows(size , "value");
THE PROBLEM WITH CODES ABOVE IS THAT IT TAKES AMOUNT OF TIME JUST TO ITERATE EACH OF THOSE CLASSES ? ANY SOLUTION TO MAKE IT FASTER ? pls help if u care :D..
You could simplify your code:
while column.contains(valueToDelete)
{
column.remove(valueToDelete);
}
You're not going to be able to speed up your ArrayList iteration, especially if your list is not sorted. You're stuck at O(n) for this problem. If you sorted it and inserted logic to binary search for the item to remove until it is no longer found, you could speed up access.
This next suggestion isn't directly related to the time it takes, but it will cause you problems.
You should never compare String objects for equality using the == operator. This will cause a comparison of their pointer values.
Use this instead:
if (iterator.next().equals(valueToDelete))
EDIT: The problem here is not the iteration. The problem is removing the elements from the ArrayList. When you remove the first element from an ArrayList, then all subsequent elements have to be shifted one position to the left. So in the worst case, your current approach will have quadratic complexity.
It's difficult to avoid this in general. But in this case, the best tradeoff between simplicity and performance can probably be achieved like this: Instead of removing the elements from the original list, you create a new list which only contains the elements that are not equal to the "valueToDelete".
This could, for example, look like this:
import java.util.ArrayList;
import java.util.List;
public class QuickListRemove
{
public static void main(String[] args)
{
List<String> size = new ArrayList<String>();
size = deleteAll(size, "value");
}
private static <T> List<T> deleteAll(List<T> list, T valueToDelete)
{
List<T> result = new ArrayList<T>(list.size());
for (T value : list)
{
if (!value.equals(valueToDelete))
{
result.add(value);
}
}
return result;
}
}
If you want to modify the collection while iterating them then you should use Iterators, otherwise you can use the for-each loop.
For -each :
// T is the type f elements stored in myList
for(T val : myList)
{
// do something
}
Try putting a break after you find the element to delete.