Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have a problem getting my JComboBox's drop down list to show a list of hotels by hotel name.
My ArrayList contains hotelNo, hotelName, city.
In my GUI, ive written this
Object[] hotelArr = { databaseconn.arrayListHere() };
#SuppressWarnings({ "rawtypes", "unchecked" })
// this just hide some unimportant warnings
JComboBox hotelList = new JComboBox(hotelArr);
hotelList.addActionListener(this);
frame.add(hotelList, BorderLayout.NORTH);
I can click the drop down list but it only shows "[]". Brackets I think they're called.
I want it to show the list of hotelName which is also stored in the ArrayList hotelInfo I've put in a method called arrayListHere.
So how do I do it? Spent many hours on this issue. Couldn't find an answer or help anywhere. I also checked the docs but didn't get anything I could use.
The way your Object[] hotelArr is defined was incorrect. Also, it's not possible to simply cast a list to an array. Instead, you must convert the list to a data structure, the JComboBox can handle. There are several posibilities:
1. (best in my opinion, because:
guarantees type safety, if you are handling classes other than Object
return type of arrayListHere() can be the interface Collection, which makes it more common, than a returned List
Collection<E> list = databaseconn.arrayListHere();
Vector<E> vector = new Vector(list);
JComboBox box = new JComboBox(vector);
2. if you stay with List as return type of arrayListHere()
Object[] array = databaseconn.arrayListHere().toArray();
JComboBox box = new JComboBox(array);
your problem is that you get a blank [] and treat is as an Array (well - hard to explain in words, i 'll use code to do so )..
//you *certainly* get an array here
Object[] list = databaseconn.arrayListHere();
//and as a result you get this code
Object[] hotelArr = new Object[]{ list } ;
when you get the message [] then certainlty that arry is empty, wich leads me to the assumption that databaseconn.arrayListHere() is an empty array
a workaround for you would be
Object[] hotelArr = (Object[]) databaseconn.arrayListHere();
but pleas check if that array before brining it to front!!
You said that your ArrayList have 3 type pf data i.e. hotelNo, hotelName, city.
& now you load it in Object[] hotelArr and then you are adding it to JComboBox.
So how application will understand that which among hotelNo, hotelName, city to take.
so make one another String[] that ll have hotelName only.
then try to load it in JComboBox, then it ll work. You can't directly add object to JCombobox when you are multiset data in Object Array.
If you are passing single set of data like hotemName then it ll work. see this :
List<String > ar = new ArrayList<>();
ar.add("hotel");
ar.add("hotel2");
ar.add("hotel3");
Object[] al = ar.toArray();
JComboBox j = new JComboBox(al);
System.out.println(j.getItemCount());
see this running example.
Related
So I am pretty new to java, and am trying to create a list in java with this:
private creatureKind[] field = new creatureKind[7];
creatureKind being another class I created within the same package. Is this the right syntax? I am trying to call functions such as set(), which
I found on this link: https://docs.oracle.com/javase/8/docs/api/java/util/List.html#set-int-E-, but I am getting an error message that abridged is saying that field is an array type. Not a frequent poster of this site so sorry if I messed stuff up in advance.
What you defined is a static array with a 7 element.
If you want to define a list, or better, an ArrayList you should it as follows:
List<creatureKind> list = new ArrayList<>();
Note that this is an unbound list, you should add values, before setting values. In general, I would suggest reading the documentations: https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html
If I understood your question correctly, you might need to do the following:
List<creatureKind> myList = new ArrayList<>();
I just wanted to clarify this question I had for a while for more efficient and 'correct' code.
I gave a class 'Student' with objects in an array list of objects. I have another class called Class which has an array list of references to the very same objects in the Student class.
Should I declare the 'Class' class as
ArrayList<Student> myStudents = new ArrayList<Student>();
or
ArrayList<Class> myStudents = new ArrayList<Class>();
Also another part of the question is I have seen people declare arrayLists as ArrayList<Student> myStudents = new ArrayList<>();
where the second half of the carrots are left empty. What exactly does the difference mean? Does this mean that the array list is not an object of any class?
Thank you so much for your time and help
Cheers
It depends on what you want to store in the list rather than where you are using it. If you're storing Student objects, then you'll use ArrayList<Student>().
The type omitted on the right side is called type inference (added in java 7), which means the type parameter on the right side will be inferred from the type of the assignment variable on the left. It helps to write the code in a cleaner way. For e.g.
Writing below is easier:
List<Some<Type<Another>>> var = new ArrayList<>();
than:
List<Some<Type<Another>>> var = new ArrayList<Some<Type<Another>>>();
Technically, neither.
You would want to do:
List<Student> myStudents = new ArrayList<>();
if you want to create an ArrayList with Student objects and
List<Class> myClasses = new ArrayList<>();
if you want to create an ArrayList with Class objects.
1) Note the variable names.
2) Note that you should always try to code to an interface (the left side is a List, not an ArrayList). This allows much greater flexibility since you're not dependent on the specific implementation of an ArrayList later on. This point is so powerful! You can write method signatures to accept objects of type List and then use an ArrayList, LinkedList or Stack or any class that implements a List. Depending on how you are using your ArrayList later, the Collection interface may be sufficient instead.
The diamond operator allows the compiler to infer the value of the type argument without having to type it all out. It's needed for backward compatibility for older Java versions.
As a general practice for performance optimization, you will also want to supply an initial capacity of an ArrayList if it's possible. So if you know that there are only 5 classes, then you would do:
List<Class> myClasses = new ArrayList<>(5);
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I'm trying to implement a stack with an Array List.
BlueJ tells me that "size" has private access in java.util.ArrayList even though the Array List is public, when I'm compiling.
int stackLength = stackStorage.size;
System.out.println(+stackLength);
And if I change the line to..
int stackLength = stackStorage.size();
the program compiles and I get a nullPointerExcetion when I run the function.
I don't understand why this is happening because a value cannot be manually assigned because the value needs to come from the stack size.
Any help appreciated, cheers.
You can't directly call for the variable (because it's a private field). You should use stackStorage.size() instead. Also make sure stackStorage is actually instantiated.
You most probably have:
ArrayList<Object> stackStorage;
However you must instantiate it somewhere like so:
stackStorage = new ArrayList<Object>();
This may also be done on the same line:
ArrayList<Object> stackStorage = new ArrayList<Object>();
Once you have created this ArrayList do note that it still doesn't have any elements in it. In order to actually add an Integer to the array simply do:
stackStorage.add(number);
And after you do that, if you call stackStorage.size() it should return 1, meaning there's one element in the ArrayList. If you wish to add more, simply use the add() method. Also make sure you add the same object as you instantiated it with. You can't store String in ArrayList<Integer> for example.
Full-code example:
ArrayList<Integer> stackStorage = new ArrayList<Integer>();
stackStorage.add(10); //Now has value `10` in `index[0]`
System.out.println("index[0]: " + stackStorage.get(0)); //Prints 10
System.out.println("stackStorage.size() = " + stackStorage.size()) //Prints 1
In your case replace Object with Integer if you wish to store integers. NullPointerException means your object is still null when you tried to call size(). This should solve your issue. If you're not sure what null is or don't quite understand what NPE(NullPointException) is I suggest reading about it and if you have further difficulties, posting it here.
That's because size is a private field and hence you don't have access to it, where size() is a public method that you can use. Therefore call size() to get the size of the ArrayList. The NullPointerException has nothing to do with size it is simple because your object is not initialized, make sure you initialize your objects before using them.
List<Something> list = new ArrayList<Something>();
size is a private variable
size() is a public method
For getting the size of the arrayList , you need to use size() and before calling size() dont forgot to intialize the array List like below .
List list = new ArrayList();
I know this is easy and can be done with 2 lines of code, but i am curious to know if there exists any such function
i have a int which tell me the size of list and i need to create a list say
List<Integer> intList;
i can create this by easily iterating through the size something like
for(int i=1 ; i <= size; i++) // started with 1 as i want it from 1
{
fill list
}
but i was just thinking as if there exists any such methods either in Collection API or Apache common
where i can pass the size to get a List with given size
Edit
May i was not able to put question in proper way, i want to get filled my list say
if size=4 than i was thinking abt something
Integer=1
Integer=2
Integer=3
Integer=4
and not an empty list with size 4
i know question do not make much sense, but still its better to clear your questions
Short answer: No
The two-liner you're currently using is already optimal.
The thing here is that List is an interface class and you can't create instances of an interface class. So before you want to construct it you need to know what kind of List you want to create. For the moment let's assume you want an ArrayList. From this moment on you can simply use the correct constructor to initialize your list e.g.
List<Integer> intList = new ArrayList<Integer>(10);
Which constructs an ArrayList of initial capacity 10.
For other kinds of list you can check the Java documentation.
To fill the list with initial data you can do something like this:
int[] myArray = new int[]{ 58,63,67,72,70,63,62,63 };
List<Integer> intList = new ArrayList<Integer>(myArray );
To answer the question after what you've added with your edit: No, there's no such method to fill a list with ascending integers in the standard collections API. You'll have to program a loop yourself and add elements to the list.
Ok basically what I am doing is i have a jtable in which users can enter their information into the table, I then want to be able to save it into a text file. The problem I am running into however is along the lines of this.
private static String dataValues[][];
I want to be able to declare dataValues like this so I can accesses it in every method so I can add rows to my jtable like this:
dataValues = {{number, owner, txtDate"}};
tableModel.addRow(dataValues);
however I get an error on the dataValues saying that "Array constants can only be used in initializers." And i dont really understand what that means.
if I declare the variable like this in the actual method it works.
String[][] dataValues = {{number, owner, txtDate}};
But I need to be able to access it anywhere in the program so declaring it like that will not help me.
Thanks for the help in advance.
The JTable represents the data internally with a TableModel. What the JTable does in the constructor is convert the initial array into the TableModel. What you need to do is think in terms of TableModels as described in the following link: http://docs.oracle.com/javase/tutorial/uiswing/components/table.html#data
You can always initialize array variables like so:
static String[] row;
and later:
row = new String[]{"foo", "bar", "baz"};
"Array constants can only be used in initializers." - is a java syntax error.
You can not use statement like :
int[] a = new int [3];
a = {1,2,3};
I think with "a = {...}" it is not clear to the "javac" compiler what the type of "a" is.
Especially when dealing with array of objects such as Strings.
So use of constants allowed are
int[] a = {1,2,3};
Or possibly
a = new int [] {1,2,3};
Above should the only way if you really want to do what you are trying to do.
Essentially, this is how your code would look like:
dataValues = new String[][] {{"number", "owner", "txtDate"}};
That for the Java syntax error part. For JTable stuff, please follow #Stphane G's answer
Have a look at this answer i had given for a question on using a generic table model. You will find using a class with the fields representing the columns of the table a very easy implementation to work with
Is there a generic TableModel we can use in JTables?