java.lang.String cannot be cast to [Ljava.lang.Object; - java

I want to call course name in combobox and print course Id which selected coursename How can I solve this problem?
public void coursename(){
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
Query query= session.createQuery("select a.courseName,a.courseId from Semester e inner join e.course as a");
for (Iterator it = query.iterate(); it.hasNext();) {
Object row[] = (Object[]) it.next();
combocourse.addItem(row[0]);
}
session.close();
}
private void combocourseActionPerformed(java.awt.event.ActionEvent evt) {
JComboBox combocourse = (JComboBox)evt.getSource();
Object row[] = (Object[])combocourse.getSelectedItem();
System.out.println("id"+row[1] );
}

By not trying to cast a String to an Object[]. Look at the return value of the methods you're using, and use variables typed appropriately to store those return values. JComboBox#getSelectedItem returns an Object (in this case apparently a String), not an array (of any kind). But in this line:
Object row[] = (Object[])combocourse.getSelectedItem();
...you're trying to cast it to be an Object[] (array of Object) so you can store it in an Object[]. You can't do that.
It seems like row should just be Object or String, not Object[], and that when you use it you should just use it directly, not as row[1]:
Object row = combocourse.getSelectedItem();
System.out.println("id"+row );
Or
String row = (String)combocourse.getSelectedItem();
System.out.println("id"+row );
In a comment you asked:
I called coursename in combobox but i should save course id in my database. How can I get courseId?
I don't know JComboBox. Fundamentally, you need to store something that contains both values (the ID and name) and then use that something when you get the selected item. Unless JComboBox has some functionality for this built in, you might need a simple class for that that holds the values and implements toString by returning courseName. Something vaguely like:
class CourseItem {
private String courseName;
private String courseId; // Or int or whatever
CourseItem(String courseName,String courseId) {
this.courseName = courseName;
this.courseId = courseId;
}
public String getCourseName() {
return this.courseName;
}
public String getCourseId() {
return this.courseId;
}
public String toString() { // For display
return this.courseName;
}
}
Then:
public void coursename() {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
Query query = session.createQuery("select a.courseName,a.courseId from Semester e inner join e.course as a");
for (Iterator it = query.iterate(); it.hasNext();) {
Object row[] = (Object[]) it.next();
combocourse.addItem(new CourseItem((String)row[0], (String)row[1]));
}
session.close();
}
private void combocourseActionPerformed(java.awt.event.ActionEvent evt) {
JComboBox combocourse = (JComboBox) evt.getSource();
CourseItem item = (CourseItem)combocourse.getSelectedItem();
System.out.println("id" + item.getCourseId());
}

try:
Object row = (Object)combocourse.getSelectedItem();
System.out.println("id"+row );
You only add single objects into the combocourse, not arrays of objects.

combocourse.getSelectedItem(); in your case returns String and string cannot be cast to array of objects. If you want to get List of Objects, they use getSelectedObjects()

Related

Using Collections and HashMap

I have the following class, its fairly simple, all i am doing is storing the variables from a URL.
class RM {
private String identifier, visible;
public String getIdentifier() {
return identifier;
}
public void setIdentifier(String identifier) {
this.identifier = identifier;
}
public String getVisible() {
return visible;
}
public void setVisible(String visible) {
this.visible = visible;
}
public RM (String identifier, //1
String visible; {
this.identifier = identifier; //1
this.visible = visible;
}
#Override
public String toString() {
return identifier + "\t" + visible + "\t";
}
}
This is stored in a collection List when i pass through the variables.
Collection<RM> attributes1 = new ArrayList<>();
I then obtain the variables stored in the identifier field and store them in an array like below:
Object rowDataprelim1 [] = new Object[1];
RM rm = null;
Iterator<RM> iterator = attributes1.iterator();
while(iterator.hasNext()) {
rm = iterator.next();
rowDataprelim1[0] = rm.identifier;
System.out.println(rm.identifier);
I then create a HashMap, the reason for doing so is because i want unique entries only.
Map<Object, Integer> numberMapping = new HashMap<>();//create a new hashmap
And also create an array of which i store identifier into rowData[0].
Object rowData[] = new Object[2];
Iterator it = numberMapping.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry) it.next();
rowData[0] = attributes1.get((int) pair.getValue()).identifier;
it.remove();
}
What i cant get right is the syntax to get the value of identifier from my collections list, i believe the syntax i have used is for an Arraylist.
rowData[0] = attributes1.get((int)pair.getValue()).identifier;
Can someone advise the correct syntax, i only want to get identifier and not the visible. I in fact have around 30 items in my class and only want to get 12 of them for the first section of my project. I have never used collection before and i have been told to use Collection and not ArrayList.
Any help is much appreciated.

How to map Integer List from result

I am using java 7 and jdbc template to query a integer array from postgresql.My code is as below:
#Autowired
private JdbcTemplate jdbcTemp;
String SQL = "select item_list from public.items where item_id=1";
List<Integer> ListOfitems=jdbcTemp.queryForList(SQL , Integer.class);
My item_list column is integer[] in postgresql.But when I try like thid it throws an error as Bad value for type int psql exception.
Any help is appreciated
You can use java.sql.Array.
If you want to get only integer array you can try like this
String SQL = "select item_list from public.items where item_id=1";
Array l = template.queryForObject(SQL, Array.class);
List<Integer> list = Arrays.asList((Integer[]) l.getArray());
Or use RowMapper
Foo foo = template.queryForObject(SQL, new RowMapper<Foo>(){
#Override
public Foo mapRow(ResultSet rs, int rowNum) throws SQLException {
Foo foo = new Foo();
foo.setName(rs.getString("name"));
foo.setIntegers(Arrays.asList((Integer[]) rs.getArray("item_list").getArray()));
return foo;
}
});
Class Foo:
class Foo {
private String name;
private List<Integer> integers;
public String getName() {
return name;
}
// ...
}
queryForList saves each row that you got as a result from your query as an element of a List. It doesn't take the list that is saved into a column and returns it for you.
From the documentation : "The results will be mapped to a List (one entry for each row) of result objects, each of them matching the specified element type."
At best you will get a List<List<Integer>> returned, but I'm not sure fi you can use List<Interger>.class as a parameter for the call.

Element's equality check from list of object

I have a List of Employee object.
class Employee{
private int empId;
private String name;
}
Now I have
List<Employee> empList = new ArrayList<Employee>();
How can I find, if my list contains an employee named "ABC"??
empList.contains("ABC"); wont work...
Should I put it in Map?? Which one is more efficient??
Just wanted to mention that I get my Employee object from database....
You can use
Map<String, Employee> map = new HashMap<>();
map.put("ABC", new Employee("ABC"));
map.put("John", new Employee("John"));
and then check
map.containsKey("ABC")
Should I put it in Map?? Which one is more efficient??
Because contains() method of list, calls indexOf, which needs to iterate over all elements
like this
public int indexOf(Object o) {
if (o == null) {
for (int i = 0; i < size; i++)
if (elementData[i]==null)
return i;
} else {
for (int i = 0; i < size; i++)
if (o.equals(elementData[i]))
return i;
}
return -1;
}
Where as map no need to iterate over all elements
Since you are storing the Employee objects and not String in your list , i think it is impossible to search without looping through all list objects
for (Employee employee : empList) {
if (employee.getName().equals(searchString))
System.out.println("Found");
}
Note: Your Employee class should give access to name field either through getter method or change it to public
There are other alternatives, but it depends on your requirements and tradeoff's between speed, space, readability, resources etc
One thing i can think of is HashMap, which has constant time lookup in average case
HashMap<Integer, String> hm = new HashMap<Integer, String>();
hm.put(1, "Tom");
System.out.println(hm.containsValue("Tom"));
Now,
Should I put it in Map?? Which one is more efficient??
Instead of coding and analyzing, Know Thy Complexities beforehand !
In Java 8, if you wanted to determine whether the employee list contains an employee named "ABC", you could do this:
boolean containsABC = empList.stream().anyMatch(emp -> emp.getName().equals("ABC"));
Override equals. You can then use List.contains
class Employee {
private empId;
private name;
public boolean equals(Object o) {
return (o instanceof Employee && ((Employee)o).empId == empId && ((Employee)o).name = name);
}
}
List l = ...;
Employee e = new Employee(...);
l.add(e);
l.contains(e);
Here is the code that you can use.
I am considering that you want list to return true when empId and name of the Employee matches.
I also prefer to use Constructor in your code(Just recommendation).
The below code will run as you are wanting it to be.
class Employee {
private int empId;
private String name;
// below overriden function will return true if it found Employee with
// same ID and name
#Override
public boolean equals(Object obj) {
return (obj instanceof Employee //Checking instace of obj
&& ((Employee)obj).empId == empId //Checking empId
&& ((Employee)obj).name.equals(name)); //Checking name
}
// Used constructor to create Employee
Employee(int id, String nm) {
empId = id;
name = nm;
}
}
Here is an example run :
List l = new ArrayList();
l.add(new Employee(1, "ME");
System.out.println(l.contains(new Employee(1, "ME"))); //print true
I would also like to acknowledge you that you should also override hashCode() when you decides to override equals(...) method according to Design Pattern.

Is it possible to retype object from object to integer

i am facing problem with the retyping the object to integer.
I have the object Car with 2 string attributes. First attribute is ID.
I retyped ID from string to integer
ArrayList<Car> intList = new ArrayList<Car>(); // already filled with objects
ArrayList<Integer> intList = new ArrayList<Integer>();
for(Car tempInt : items){
intList.add(Integer.parseInt(tempInt.getID()));
}
Collections.sort(intList); // i sorted id's
Can i retype the integer back to Car object?
for (ItemObject temp : intList) { // HERE I GET THE ERROR
if(temp instanceof Car){
System.out.println("ID : "+((Car)temp).getID())
}}
Is this possible? I need sort objects.
Thanks.
S
I think you are fundamentally misunderstanding which objects are which in this scenario. When you create your ArrayList<Integer> you do not magically preserve any information about which cars those integers were connected to.
I think what you want to do is sort your list of Cars by id, correct? In that case, what you want is a Comparator: http://docs.oracle.com/javase/6/docs/api/java/util/Comparator.html
Here is an example of sorting using a Comparator:
ArrayList<Car> cars = ...//Filled with cars
Comparator<Car> carSorter = new Comparator<Car>() {
#Override
public int compare(Car a, Car b) {
return a.getID() - b.getID();
}
};
Collections.sort(cars, carSorter);//After this line, cars will be in order
I wouldn't do it this way at all. If you instead allow cars to be able to compared to each other (by storing the id as an Integer, the Cars can sort themselves. Do it like this:
public class Car implements Comparable<Car> {
private String id;
private String otherString;
private Integer intId; // this is new
public Car(String arg0, String arg1) {
// Add this line to constructor
intId = Integer.parseInt(id);
}
#Override
public int compareTo(Car arg0) {
return intId.compareTo(arg0.intId);
}
}
Then, just do:
Collections.sort(carList);

Convert an ArrayList to an object array

Is there a command in java for conversion of an ArrayList into a object array. I know how to do this copying each object from the arrayList into the object array, but I was wondering if would it be done automatically.
I want something like this:
ArrayList<TypeA> a;
// Let's imagine "a" was filled with TypeA objects
TypeA[] array = MagicalCommand(a);
Something like the standard Collection.toArray(T[]) should do what you need (note that ArrayList implements Collection):
TypeA[] array = a.toArray(new TypeA[a.size()]);
On a side note, you should consider defining a to be of type List<TypeA> rather than ArrayList<TypeA>, this avoid some implementation specific definition that may not really be applicable for your application.
Also, please see this question about the use of a.size() instead of 0 as the size of the array passed to a.toArray(TypeA[])
You can use this code
ArrayList<TypeA> a = new ArrayList<TypeA>();
Object[] o = a.toArray();
Then if you want that to get that object back into TypeA just check it with instanceOf method.
Yes. ArrayList has a toArray() method.
http://java.sun.com/javase/6/docs/api/java/util/ArrayList.html
Convert an ArrayList to an object
array
ArrayList has a constructor that takes a Collection, so the common
idiom is:
List<T> list = new ArrayList<T>(Arrays.asList(array));
Which constructs a copy of the list created by the array.
now, Arrays.asList(array) will wrap the array, so changes to the list
will affect the array, and visa versa. Although you can't add or remove
elements from such a list.
TypeA[] array = (TypeA[]) a.toArray();
Using these libraries:
gson-2.8.5.jar
json-20180813.jar
Using this code:
List<Object[]> testNovedads = crudService.createNativeQuery(
"SELECT cantidad, id FROM NOVEDADES GROUP BY id ");
Gson gson = new Gson();
String json = gson.toJson(new TestNovedad());
JSONObject jsonObject = new JSONObject(json);
Collection<TestNovedad> novedads = new ArrayList<>();
for (Object[] object : testNovedads) {
Iterator<String> iterator = jsonObject.keys();
int pos = 0;
for (Iterator i = iterator; i.hasNext();) {
jsonObject.put((String) i.next(), object[pos++]);
}
novedads.add(gson.fromJson(jsonObject.toString(), TestNovedad.class));
}
for (TestNovedad testNovedad : novedads) {
System.out.println(testNovedad.toString());
}
/**
* Autores: Chalo Mejia
* Fecha: 01/10/2020
*/
package org.main;
import java.io.Serializable;
public class TestNovedad implements Serializable {
private static final long serialVersionUID = -6362794385792247263L;
private int id;
private int cantidad;
public TestNovedad() {
// TODO Auto-generated constructor stub
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getCantidad() {
return cantidad;
}
public void setCantidad(int cantidad) {
this.cantidad = cantidad;
}
#Override
public String toString() {
return "TestNovedad [id=" + id + ", cantidad=" + cantidad + "]";
}
}

Categories

Resources