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.
Related
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
I'm a second year Java student, and I'm learning various things on my own time. One of these is JList.
jList1.getSelectedValue();
The above code returns an Object, not a String. I need a String of the selected list item. Adding/removing models from the listbox is not a problem. The list's contents are constantly changing (with the model), so using .getSelectedIndex() as a work-around is undesirable.
Help?
EDIT: I do have a listener working for the jList, I just need this one problem solved.
Just use a cast, or the toString method as Andrew mentioned in his comment:
String val = (String)jList1.getSelectedValue();
or:
String val = jList1.getSelectedValue().toString();
Method getSelectedValue() from class JList returns selected object which you've added in ListModel. Either it can be a String,Integer or any other Object.
If you generate a JList like this
String[] data = {"one", "two", "three", "four"};
JList myJList = new JList(data);
select method myJList.getSelectedValue(); obviously return a string.
If you add your own objects like Student or Department, you get the same object when selection and when you try to print it the hashCode reference of the object would be printed unless you overwrite toString() method in your own class.
You could either cast the returned Object to String, given you already filler the list with String values. Alternatively you could deal with the list through the ListModel, but either using the DefaultListModel (Also handles data as Objects) or implementing your own ListModel to provide what ever functionality you need such as restricting the list data types to String.
I used .toString() or casting to string but I received the address of the selection, not the the values. So I tried this code, and it did work:
private class ButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String a[] = new String[20];// To save the selections
int i = 0, j = 0;
// Get the selected values.
Object[] selections = array2List.getSelectedValues();
// To save the selections in array
for(Object selections : sugCoursesList.getSelectedValues())
{
for(String t : array2)
{
if (selections == t)
{
a[i] = t;
i++;
System.out.println(selections);
}
}
}
for(String s: a)
System.out.println("a " + s);
}
I have compared the array that was in the list to check if it is selected if yes save it in array a.
I have an ArrayList of objects (A class called OrderItem). OrderItem has a toString() method in it.
I also have a GUI class in which I have a JList. I want to list all the toString()'s for the elements of the arrayLists.
I know that for an arrayList of strings you can make them show in a JList by using:
ArrayList<String> myArrayList = new ArrayList<String>();
myArrayList.add("Value1");
myArrayList.add("Value2");
myJList = new JList(myArrayList.toArray());
But I want to list the toString() methods of an object arrayList, i.e. have something like:
ArrayList<OrderItem> myArrayList = new ArrayList<OrderItem>();
myJList = new JList(myArrayList.toString());
I realise that there is a possibility that JList doesn't support such a feature or that there is some sort of logic problem with this. If that is so could you inform me as to why? Because surely an arrayList of strings should work in a similar way to an object arrayList's toString(). I merely want to be pulling out a String value for the elements and using those values for my list.
I've searched the web for an answer and have not been able to find one that helps me, so I've come here to try to get this resolved.
Thanks a lot!
By default, JList shows the toString value of the object. So there is no need to convert your objects to strings.
You can override that behavior of JList if needed by creating custom cell renderers. See How to Use Lists for more details.
You can convert the list to an array and then put it in the list.
ArrayList<OrderItem> myArrayList = new ArrayList<OrderItem>();
OrderItem[] items = new OrderItem[myArrayList.size()];
myArrayList.toArray(items);
myJList = new JList(items);
Actually, the toArray() method displays each item in the arrayList. JList doesn't show anything by default. You have to set the visibility according to your needs.
It sounds like you are trying to simply display the object's toString method in the list instead of the full object; in other words, you simply want to display the string representation. instead of the array representation.
You can rewrite the array to represent the data you want to show (provide the "toString construct as the array is built):
ArrayList<> myNewArrayList = new ArrayList<OrderItem>();
for (int i=0; i< oldArray.size(); i++)
{
newArray.add(oldArray.get)i).toString();
}
... rest of code ...
Then use the new array in the panel and use the index as reference to the object array for object processing.
HTH
LLB
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.
I know the title sound confusing and thats because it is. its a bit long so try too stay with me.
this is the layout i have my code designed
variables
constructor
methods.
im trying too fill a Jlist full on names. i want too get those names using a method. so here goes.
in my variables i have my JList. its called contactNames;
i also have an array which stores 5 strings which are the contacts names;
heres the code for that anyway
String contact1;
String contact2;
String contact3;
String contact4;
String contact5;
String[] contactListNames;
JList contactList;
simple enough. then in my constructor i have the Jlist defined to fill itself with the contents of the array
String[] contactListNames = new String[5];
JList contactList = new JList(contactListNames);
fillContactList();
that method fillContactList() is coming up shortly.
now heres where stuff gets balls up.
ive created three different methods all of which havent worked. basically im trying to fill the array with all of them.
this is the simplest one. it doesnt set the Jlist, it doesnt do anything compilicated. all it trys too do is fill the array one bit at a time
public void fillContactList()
{
for(int i = 0;i<3;i++)
{
try
{
String contact;
System.out.println(" please fill the list at index "+ i);
Scanner in = new Scanner(System.in);
contact = in.next();
contactListNames[i] = contact;
in.nextLine();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
unfortunately this doesnt qwork. i get the print out to fill it at index 0; i input something and i get a nice big stack trace starting at
contactListNames[i] = contact;
so my question in short is
why cant i fill the array from that method.
***********************************************888 ***********************************************888
stack trace by request
please fill the list at index 0
overtone
please fill the list at index 1
java.lang.NullPointerException
at project.AdminMessages.fillContactList(AdminMessages.java:410)
at project.AdminMessages.<init>(AdminMessages.java:91)
at project.AdminUser.createAdminMessages(AdminUser.java:32)
at project.AdminUser.<init>(AdminUser.java:18)
at project.AdminUser.main(AdminUser.java:47)
To define an array in a constructor you can do something along these lines,
// if values are predefined, you can explicitly fill the array
String[] contacts = {"Bill Gates", "Steve Jobs", "Jon Skeet"};
// or this way, both will work.
String[] contacts = new String[2];
Looking at JList from the Java Doc's you can most certainly pass in an array to JList
String[] data = {"one", "two", "three", "four"};
JList dataList = new JList(data);
You are getting NullPointerException because the array, contactListNames is not initialized, you would need to initialize it.
You define an array in a constructor just like you would any other variable. So, it would look something like:
// define an array of size 3
String[] contactListNames = new String[3];
The reason you are getting exceptions is because you don't actually initialize the array. You declare it but you never set it to a value (or give it a size). You should post the stack trace of the error but I suspect it's a NullPointerException.
Then in my constructor i have the
Jlist defined to fill itself with the
contents of the array
String[] contactListNames = new String[5];
JList contactList = new JList(contactListNames);
fillContactList();
What you're doing here is creating new local variables that are shadowing the ones defined in your class.
Change it to:
contactListNames = new String[5];
contactList = new JList(contactListNames);
fillContactList();