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.
Related
I have made an ArrayList SYMTAB and i wanted to add element in it. But I am not able to understand this TableRow working inside the add. I am not able to get the idea of how it is working or what it is returning.
Another class is created named TableRow and there i have defined the constructors.
What is this code new TableRow(parts[1], Integer.parseInt(parts[2], Integer.parseInt(parts[0]) returning or doing ?
ArrayList<TableRow> SYMTAB = new ArrayList<>();
SYMTAB.add(new TableRow(parts[1], Integer.parseInt(parts[2], Integer.parseInt(parts[0]));
TableRow.java
public class TableRow{
public TableRow(String symbol, int address,int index) {
super();
this.symbol = symbol;
this.address = address;
this.index=index;
}
}
Ok probably I will get some minuses here but the importance is to understand :
Here : Your array list has a type TableRow which means you can add only that kind of object there . How do you initialize an object ? new TableRow() , but your constructor has some parameters also which means : it needs a String , an int and another int . Now if you lok carefully your parts is mostly a String[] type . Every index of it brings a single string according to the length of your array of String[] . Since your constructor needs a string and 2 integers , the Integer.parseInt(parts[2]) is just converting those strings into ints ? Does this help you ?
assuming parts is your arguments, this line is creating a new object type TableRow. and adding that object in ArrayList which is type of TableRow. ArrayList is a collection of TableRow objects.
ArrayList<TableRow> SYMTAB = new ArrayList<>(); // initializing Arraylist type TableRow
SYMTAB.add(new TableRow(parts[1], Integer.parseInt(parts[2]), Integer.parseInt(parts[0])); //creating new object of tableRow and adding it to Arraylist.
I need to use an array list as I don't know how many rows I will need but I know I'll need 2 columns. I'm unsure of how to create such an array list, add to both columns and read data from both columns. Both columns will contain integers.
I have seen some suggest:
ArrayList<Arraylist<Integer>> name = new ArrayList<ArrayList<Integer>>();
but I can find an explanation of how to add to both columns.
I've also seen:
ArrayList<Integer[][]> name = new ArrayList<Integer[][]>();
and different variations of where and the number of square brackets.
Thanks.
Java is Object Oriented language, so why not create ArrayList<Column> ?
You can create a class Column which will cover your requirements: it can have setters and getters, and if you need to support other types other than Integer you can generify it. For example:
class Column<T> {
private T value;
public Column(T value) {
this.value = value;
}
public getValue() {
return this.value;
}
}
Then you declare:
List<Column<Integer>> list = new LinkedList<>();
list.add(new Column<Integer>(5));
System.out.println(list.get(0).getValue())
Example how create two dimension structure use lists like you to do:
List<List<Integer>> names = new ArrayList<>();
List<Integer> row = new ArrayList<>();
row.add(1); // first column
row.add(2); // second column
names.add(row); // add row with column
System.out.println(names.get(0).get(0)); // get first column from first row
System.out.println(names.get(0).get(1)); // get second column form first row
But best way is use Custom object like this:
class CustomRow {
private int col1;
private int col2;
// getters and setters
}
List<CustomRow> tables;
CustomRow cr = new CustomRow();
cr.setCol1(1);
cr.setCol2(2);
tables.add(cr);
Something like this:
public MyObject {
Integer integer1;
Integer integer2;
}
List<MyObject> myObjList = new ArrayList<>();
MyObject mo = new MyObject(){
...
myObjList.add(mo);
You could try
a Map and use the key and the value to hold values
a List of tuples
a List of Lists as you suggested
You didn't give enough information as to what you actually want to do, but if you have to use a List as a base, I'd typically go with a List of custom Tuple objects, each holding two values.
You can try creating a simple POJO class called Row and have two variables as column1 and column2. Then add this Row object to your list.
You basically need to create an ArrayList that holds an ArrayList of type Integer. You can then add two of these ArrayLists into the main array list.
List<List<Integer>> myList = new ArrayList<>();
List<Integer> x = new ArrayList<>();
x.add(5);
x.add(6);
List<Integer> y = new ArrayList<>();
y.add(5);
y.add(6);
myList.add(x);
myList.add(y);
Based off this answer:
How do I declare a 2D String arraylist?
So this is something that has me a little stumped. I'm trying to make an array list that holds objects, and each object will have a string associated with it.
For an example lets say I have this array list of adjacent rooms...
ArrayList<Object> adjacentRooms = new ArrayList<Object>();
I could add Room objects to that array list that are adjacent to whichever subject.. however, when I add to the array list with adjacentRooms.add(x); (where x could be an object Room type).. I would also like to add a string to that position. For example adjacentRooms.add(x, "north");.. <- now I know that that is not possible unless I do something like a 2D array list possibly?
So after some time researching I am at a loss. I just can't quite figure out how to add an object with an associated string in a 2D array list...
Instead of a List use a Map: That can "map" a value to another, and store it in a collection.
Something like this:
Map<String, Room> adjacentRooms = new HashmMap<>();
adjacentRooms.put("north", room);
adjacentRooms.get("east");
You may want to use constants, to make sure the values are "discrete".
It has a drawback, tho: it cannot assign more than 1 value to a key, that is more than 1 Rooms to a direction...
An ArrayList can only hold one data type. But I'm curious as to why you cant associate a string as a member in the Object you're talking about. Since you want a 2d arraylist, I'm assuming the string and "room" are related
Object foo = new Object();
foo.data = "your string"
adjacentRooms.add(foo);
access by
adjacentRooms.get(index).data
However, if you must, you can do a 2d ArrayList, but they get annoying
ArrayList<ArrayList<String> > list = new ArrayList();
access would be something like list.get(i).get(k) with 'i' referring to the index of ArrayList of Strings, and k referring to the index of a String in that 'i' ArrayList.
However, that structure does not store the "Object" you're talking about...
Hope that helps.
The "array" in ArrayList describes the way the list is implemented.
A List is always one-dimensional. When you need more dimensions, use objects in your list that can store additional information.
So either create a new class that holds your data (e.g. DetailedRoom with members Room and a String) or use an existing collection class. The latter would be a poor design, but still... it could be List for instance, so that you end up with List<List<Object>>
.
If you are to create your own class.. this is what I did...
public class AdjacentRoom {
private Room room;
private String direction;
public AdjacentRoom(Room room, String direction) {
this.room = room;
this.direction = direction;
}
public Room getRoom(){
return room;
}
public String getDirection(){
return direction;
}
}
Also for sake of example here is a bare bones room class...
public class Room {
private String name;
public Room(String name){
this.name = name;
}
public String getName(){
return name;
}
}
What this all allows me to do is ...
//Firstly i can create a room...
Room testRoom = new Room("Test Room");
//If i change my array list in the question to an AdjacentRoom list...
ArrayList<AdjacentRoom> adjacentRooms = new ArrayList<AdjacentRoom>();
//I can add rooms and strings to it like this..
adjacentRooms.add(new AdjacentRoom(testRoom, "north"));
Now I can still access each of the rooms methods while also printing each string or 'direction' associated to each room.. For example..
for(AdjacentRoom room : adjacentRooms){
System.out.println(room.getRoom().getName() + " " + room.getDirection());
}
While this is a cool and customization solution, using a map like in Usagi Miyamoto's answer ( link ) is great for this situation.
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)
I'm having a config entry, from which I'm loading into an String array like
String s = "abc$#def$#ghi";
String[] scbHLNewArray = s.split("\\$\\#");
Here I'm comparing a string with the array values after splitting it like ,
for(String arrNewErrorInfo : scbHLNewArray) {
LOG.info("SCB HL New Error Value :"+arrNewErrorInfo+"\n");
if(errorInfo.equals(arrNewErrorInfo)) {
LOG.info("SCB HL Matched New value is :"+arrNewErrorInfo);
newState = ApplicationState.NEW;
addApplicationEvent(application.getId(),comment, ApplicationEventType.COMMENT,BBConstants.AUTOBOT);
scbHLNewStatus = "Matched";
break;
}
}
I want to use some util classes like List.. Any idea on append to list and compare the string with the list objecT?
Thanks,
Nizam
you can do this with List contains method.
ArrayList<Integer> arrlist = new ArrayList<Integer<(8);
// use add() method to add elements in the list
arrlist.add(20);
arrlist.add(25);
arrlist.add(10);
arrlist.add(15);
// list contains element 10
boolean retval = arrlist.contains(10); // It will return true.
Ok, let's try... First of all, you can create a List Object, wrapping your array very easily:
List<String> myList = Arrays.asList( scbHLNewArray );
Be carefull, because you can NOT add to this list, as it only wraps your array. If you want a list you can add to, you would have to create a new one, for example:
List<String> myModifiableList = new ArrayList<String>( myList );
This will create a new List that contains all the Strings from the first one but is also modifiable (you can add Strings, if you want).
In any case, you can use "contains", as Pratik has already shown, to test if a String is inside your list:
if (myList.contains("someString")) { ... }
This works because the String class already has well implemented equals(...) and hashCode() methods. If you want to put other Object than Strings into your list, you would have to make sure that these methods are implemented well, otherwise contains might not work as expected.
Yes you can use a list of course, you need to :
1. Take the result of split as an array.
2. Then convert this array to a list.
String s = "abc$#def$#ghi";
String[] scbHLNewArray = s.split("\\$\\#");
List<String> list=Arrays.asList(scbHLNewArray); //convert the array to a list
Take a look at Arrays.asList(Array a) and this Tutorial for further information about it.
And then to search the wanted String object you can use indexOf(Object o) or contains(Object o) List methods