JList to list toString() of an ArrayList of Objects - java

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

Related

Custom method for ArrayList

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.

How to replace contents of arraylist with the contents of another arraylist?

I want to replace the contents of one arraylist with the contents of another completely.
For instance,
ArrayList<String> old = new ArrayList<String>();
ArrayList<String> newlist = new ArrayList<String>();
old.add("Hi");
old.add("World");
newlist.add("League")
newlist.add("OfLegends"):
old = newlist;
When I try that, it does this odd behavior where the arraylist's size doubles with more elements. I don't want an arraylist twice the size of the original arraylist, I just want the old arraylist to be overriden with the new arraylist, where the contents of old and new arraylist are identical. Is there a way to do this without some sort of loop, or is that my only option? Thank you and pleae
old.clear();
old.addAll(newList);
This will clear the old list and add copies of the references from newList to the old list. If you make changes to the old list, the new list will stay unaffected (and vice versa) .
Note as your code stands, you are setting the old list to the same object reference as the new list. Changing one of those lists (with an add() or remove()) will change the other as they share the same underlying object.
I tried the following:
ArrayList<String> old = new ArrayList<String>();
ArrayList<String> newList = new ArrayList<String>();
old.add("Hi");
old.add("World");
newList.add("League");
newList.add("OfLegends");
System.out.println(old.toString());
old = newList;
System.out.println(old.toString());
System.out.println(newList.toString());
And my output was :
[Hi, World]
[League, OfLegends]
[League, OfLegends]
So it seems like your code is working.
This is the constructor you’re looking for:
http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#ArrayList(java.util.Collection)
public ArrayList(Collection<? extends E> c)
Constructs a list containing the elements of the specified collection, in the order they are returned by the collection's iterator.

How can add an element to an array?

I wrote this code with a String array:
public static String[] prgmNameList = {"bbbbb", "aaaaa"};
My question is now, how can I add a new item to that array like this:
prgmNameList.add("cccc");
prgmNameList is an array. The size of an array object cannot be changed once it has been created. If you want a variable size container, use collections. For example, use an ArrayList :
List<String> prgmNameList = new ArrayList<String>(3);
prgmNameList.add("bbbb");
That said, if you insist on using an array, you will need to copy your initial array into a new array for each new element that you want to add to the array which can be expensive. See System#arrayCopy for more details. In fact, the ArrayList class internally uses an array that is expanded once it is full using System.arrayCopy so why reinvent the wheel? Just use an ArrayList
On simpler terms, note these following points:
Array size is always fixed.(In your example you fixed the array size to 2 by adding 2 elements)
Arrays operate based on index starting from '0' zero, like - prgmNameList[0] will return 1st element added in the array
Array size cannot be changed at any point of time. If you need size to be variable, choose one of List implementations
ArrayList is the best option for your need that can define itself as an 'Array that can shrink or grow'
Sample code:
public static List<String> prgmNameList= new ArrayList<String>();
prgmNameList.add("bbb");
prgmNameList.add("bbb");
prgmNameList.add("ccc");
prgmNameList.remove("bbb"); //Removes by object resolved by equals() method
prgmNameList.remove(2); //Removes by index
You have created an Array which can not grow as it's fixed in size.
You need to create a list in order to add new elements as shown below.
List<String> prgmNameList = new ArrayList<String>();
prgmNameList.add("aaaa");
prgmNameList.add("bbbb");
prgmNameList.add("cccc");
You have to use ArrayList like that
ArrayList<String> al = new ArrayList<>();
// add elements to the array list
al.add("C");
al.add("A");
al.add("E");
al.add("B");
if you want to use array as you did you have to know the number of elements that you want to add
String[] myList = new String[10];
and then
myList[4]="AA"
--
this is not possible to add to myList.
I explain you how ArrayList works and then you will understand.
ArrayList is an class that contains Array from objects. every time you add it check if it have place to store the data in the array if not it creates new array bigger and store the data.
So ArrayList this is the solution (or any other list)
if you want to add to myList you will have to implement arratList..
The method you are looking for is defined for a Collection, but you are using an array with an array initializer.
I suggest switching to the List:
public static List<String> prgmNameList= new ArrayList<>(Arrays.asList("bbbbb","aaaaa"))
Then you can call add on it because now it is a list.
Btw.: Try to prevent having mutable variables in static variables.

Java jList1.getSelectedValue() returns an Object. I need a String from the selected list item.

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.

Setting a list equal to list using equal sign or copy constructor?

This is a simple question but if I do
List<Object> list = getObjectsFromDatabase();
This would not be the correct way to handle this?
But this would?
List<Object> firstList = getObjectsFromDatabase();
List<Object> list = new ArrayList<Object>(firstList);
Or if I had a class
public class ReportDisplayModel<T> {
public ReportDisplayModel(List<T> data) {
this.data = data;
}
public List<T> data;
}
And I wanted to set the data in this model I would use the constructor?
ReportDisplayModel<Object> model = new ReportDisplayModel<Object>(getData());
Instead of
ReportDisplayModel<Object> model = new ReportDisplayModel<Object>();
model.data = getData();
Just need a clarification. Thanks.
It depends entirely on what getData() returns.
usually it is made to return Collections.unmodifiableList(result) so that clients can't modify the result.
if this result is not used anywhere else, and modifications to it doesn't mess with anything, it is fine to use the result as-is
It is rarely needed to use the copy constructor - use it when you are sure that modifying the data will impact some other component.
Regarding
List<Object> list = getObjectsFromDatabase();
vs
List<Object> firstList = getObjectsFromDatabase();
List<Object> list = new ArrayList<Object>(firstList);
either approach is fine. Depends on if you want list to refer to the list returned by getObjectsFromDatabase() or if you want it to refer to a copy of it.
If simply want to, say, print the database objects, the first approach is fine.
If you want to, say, filter out half of the database objects (i.e., remove objects from the list), and you can't say for sure that getObjectsFromDatabase() returns a mutable list, then you'll have to go with the second approach.
Regarding
ReportDisplayModel<Object> model = new ReportDisplayModel<Object>(getData());
vs
ReportDisplayModel<Object> model = new ReportDisplayModel<Object>();
model.data = getData();
I'd prefer the first method. Simply because I wouldn't want to worry about null pointer exceptions etc if I accidentally do something like
ReportDisplayModel<Object> model = new ReportDisplayModel<Object>();
model.printData();
model.data = getData();
I don't quite get your question, but I'll give it a try.
The main difference is that using the copy constructor creates a new independent copy of the list, i.e.
List<Object> firstList = getObjectsFromDatabase(); // firstList is the list returned by the database
List<Object> list = new ArrayList<Object>(firstList); //list is an independent copy of firstList
Now if you change firstList the list returned by getObjectsFromDatabase() would be changed as well (or would throw an exception if changes are not supported). On the other hand list could freely be changed without the original list being affected.
Avoid using the equal sign, because it breaks encapsulation (bad practice). Go for the copy constructor (best practice).

Categories