I think it can be explained better with example:
I have arrayLists by names sname,stime,snumber,etc., each carrying different values
and a dynamic string 'dString' that is a concatenation of "s" and a variable VR that carries (name, time, number, etc.).
Bbased on the value of VR i get from a loop, i'd like to use respective arraylist in a method. How can i use dString to refer to respective arraylist?
ArrayList<String> sname = new ArrayList<>();
ArrayList<String> stime= new ArrayList<>();
ArrayList<String> snumber = new ArrayList<>();
String[] VR = {"name","time","number"};
for(String str:VR) {
String dString = "s"+str;
String temp= dString.get(2); //How to get this?
}
(This is just as an example. the arraylists aren't empty. it's a long program so i haven't included it).
The answer is: you should be using a Map.
That is the data structure that Java offers you to map a value (for example a List of Strings) to a key (for example: a String).
In other words: don't invent your own "dictionary", when the language already offers that concept to you.
Beyond that, the real answer would be to go "full" OOP. Meaning: you shouldn't have three different lists that together describe some object (linked by a common index). Instead you rather create a class that has name, title, and number fields. So that you only hold one list of such objects.
Related
Hello I would like to make a custom method for ArrayList class.
So lets say I make a new ArrayList.
ArrayList<String> list = new ArrayList<String>
I would like to make a method I can call on list.
Something like this:
list.myMethod();
What I want to solve with my method is so you can get an Object by Object name and not index inside the ArrayList.
So basically I want to make a method returning following:
list.get(list.indexOf(str));
To sum it up:
ArrayList<String> list= new ArrayList<>();
String str = "asd";
String str2 = "zxc";
list.add(str2);
list.add(str);
System.out.println(list.get(0));
System.out.println(list.get(list.indexOf(str)));
Will print: "asd" "asd".
So instead of writing: list.get(list.indexOf(Object))
I would like to be a able to write list.myMethod(Object) and get the same result. I hope you understand my question. I know this is probably a dumb solution and I could just use a Map. But this is for learning purpose only and nothing I will use.
Custom method >>
public class MyArrayList<E> extends ArrayList<E> {
public E getLastItem(){
return get(size()-1);
}
}
How to use it >>
MyArrayList<String> list= new MyArrayList<>();
String str = "asd";
String str2 = "zxc";
list.add(str2);
list.add(str);
System.out.println(list.getLastItem());
what you need requires to extend the ArrayList classs, but you should consider using instead a
Map<String, Object>
with that approach you can do something like
myMap.get("myObject1");
You should just extend the ArrayList class creating your own with the new method. But the performance would be horrible if your list grow too much. The indexOf method have O(n), so greater is the size of your array longer is the time you have to wait.
May be you should choose a different collection if you want access directly to the element. In your case, it elements stored in the collection are unique, you could use a Set.
On the other hand, a Set does not preserve the insertion order. I don't know if this is a think you have to care of.
And a Set just let you know if the element is contained into the collection.
Another collection that can be of your interest is the Map, this is a key-value collection.
But given that you have only keys this it seems not be your case.
I have 10 array lists and a String variable.
I have one function/method that allows the user to select one of the array lists to add to. Currently, that function changes the value of a string "chosen" to the value of the proper array list name.
Another function is started in which adding elements to the arraylist happens. However, I am struggling to come up with a solution on how to change which arraylist is being added to based upon what was selected by the user.
This code doesn't work but say it was:
chosen.add(whatUserEntered);
Normally you can put in the arrayList name and add .add(whateverTheUserIsEntering) and itll work fine.
So how can I have the name of an arrayList equal that of a String variable's value?
Here is an example using a Map to bind string names to lists. When you need to put things together at run time (as opposed to compile time, as you show with your example choosen.add(userEntered)), you usually need to use a Map.
This works with strings read from a file (say to bind XML names to objects) or things like interpreters where you have to keep track of user variables by name.
public class SymbolTableExample
{
public static void main(String[] args) {
// Some array lists
ArrayList<String> cats = new ArrayList<>();
ArrayList<String> dogs = new ArrayList<>();
ArrayList<String> beetles = new ArrayList<>();
ArrayList<String> cows = new ArrayList<>();
// Bind names to them
Map<String,List<String>> binding = new HashMap<>();
binding.put( "cats", cats );
binding.put( "dogs", dogs );
binding.put( "beetles", beetles );
binding.put( "cows", cows );
// Pretend the user enters some input here
String userChoice = "cats";
String userEntered = "flufy";
binding.get( userChoice ).add( userEntered );
}
}
Use a Map.
public interface Map<K,V>
You can use the method
V put(K key, V value)
to assign a value to a key, so you can set ArrayLists for different keys or add new ones..
Since you are using ArrayLists, you could make your make your Map like so:
Map<String, ArrayList<String>)> myArrays
Then, to add a value to an array with a given key, use
myArrays.get(userChosenArrayKey).add(whatUserEntered)
So I am currently having a problem understanding how to access a set, is that even allowed? So I understand my set of names contains a set of Character objects. I also understand that my toString() method call converts these Character objects into a String, but not a conventional string -- which is why I have [s,a] rather than [sa]. So my question is, is if there is a way to make me have a list of individual strings. So I want my list to be = [s, a] rather than [ [s,a] ]. Is this even possible? I apologize if this makes no sense; nevertheless, if you do understand my fumbled explanation thank you for your time and help. If you need for me to explain more, I will.
//this all works
Set<Character> names = find(prefix).getRollCall().keySet();
//[s,a]
String lists = names.toString();
//[s,a]
List<String> sloop = Arrays.asList(lists);
//[[s,a]]
If you want to convert a Set<Character> to a List<Character> you can do
List<Character> list = new ArrayList<Character>(set);
If you want to convert a Set<Character> to a List<String> you can do
List<String> list = new ArrayList<String>();
for (char c : set)
list.add("" + c);
Don't use toString() at all. Iterate over the elements of the Set and build up whatever string you like.
Set<Character> names = find(prefix).getRollCall().keySet();
for (Character c : names)
{
// whatever you like
}
Let me explain what's happening in your code, in case you aren't clear:
String lists = names.toString();
This calls the standard toString method for a collection which converts your set to an ordinary (conventional) string in a standard format (i.e. comma delimited, in brackets). There's nothing special about the string that is created: "[s, a]".
List<String> sloop = Arrays.asList(lists);
The asList method takes one or more arguments and converts them into a list. Because you've given it only a single argument lists it creates a list with a single string element: ("[s, a]")
Then, later, I suspect you are doing something like:
System.out.println(sloop);
This again calls the standard toString method for a collection (in this case the List sloop) and again creates a comma delimited, bracket enclosed standard string: "[[s, a]]"
So, most of that is probably not what you want. Your lists variable isn't a List, it's a String which I assume isn't what you want.
If you are just looking to convert your set of character to a list of strings, then this is pretty trivial in Java 8:
List<String> lists = names.stream().map(Character::toString).collect(Collectors.toList());
I am trying to add 100 (realistically more) Strings to an ArrayList. Instead of adding each String individually, how can I use something like a for loop to add them at once. The code below is an example.
ArrayList<String> strings = new ArrayList();
String s1 = "Apple";
String s2 = "Banana";
String s3 = "Pear"
/*
More Strings created until the 100th String
.
.
.
*/
String s100 = "Kiwi";
//for loop to try add each String to List
for(int i=0; i<100; i++)
{
//Code to add each String to the arraylist
}
Can anyone identify the how I can add each String to the list?
Thanks much appreciated
Well, you could create a sophisticated strategy using reflection to fetch all variables of a given class and add them to a List; subsequently, you could loop this List and do whatever you want.
However, I do not think it would solve your problem. Indeed, you are likely to run into several pitfalls.
I would change your approach to the problem. Create a static List and add whatever you need there (or a Singleton, it depends how you want to manage this List). Once you have the list of objects you can loop it.
Cheers,
From your comments you are dealing with custom objects. Regardless of how you want to transfer data from the objects into your ArrayList, better to use a collection. The type of the collection will depend on the source of your object data. As the data is hard-coded you could use an array. Multiple variables like these
String s1 = "Apple";
String s2 = "Banana";
String s3 = "Pear"
become
String[] fruitArray = {
"Apple",
"Banana",
"Pear"
...
};
Then to add:
for (String fruit: fruitArray) {
strings.add(fruit);
}
As already stated my comment above, a cleaner design would be to to use a single List<MyObject> to contain all objects in a DRY approach and just extract a String as needed.
I have a Arraylist: ArrayList<PlayerBean> playerlist = new ArrayList<PlayerBean>();
from an Object that includes a String and an double (Name and points).
public class PlayerBean{private String name;private double points;}
However for one of my Spinners I want to show only the name (String) in my Arraylist.
How do I manage to delete(remove) the double(points)?
I tried this without any success any ideas?
I am using the swinger for android. any idea?
ArrayList<PlayerBean> playerlist = new ArrayList<PlayerBean>();
List<String> namesOnly = filterNames(playerlist);
private List<String> filterNames(ArrayList<PlayerBean> playerlist12) {
List<String> names = new ArrayList<String>();
for(PlayerBean b : playerlist12)
{
names.add(b.getName());
}
return names;
}
Your list contains PlayerBean objects and you can't temporarily delete member variables from objects. Thus you can't remove points from the list.
You could either use a List<String> instead or provide a spinner model that only displays the name. I assume you're using Swing, don't you?
Rather than removing them, why don't you make a new array List of String type, and assign all the names into this list. So you don't have any points.