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 + "]";
}
}
Related
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.
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()
I wrote a class that is to be stored in a linkedlist, with 3 fields in the class. One of these fields is a String, which I would like to search for in the linked list.
Example
LinkedList
Obj1
String name = "first";
int age = 2;
int size = 4;
Obj2
String name = "second";
int age = 3;
int size = 6;
Obj3
String name = "third";
int age = 5;
int size = 8;
If this is the linkedlist storing these three objects with the given fields, is there a way to search the linked list for the object with the name "second"?
You can search for an item in the list by iteration
// Iterate over each object within the list
for(YourClass obj : yourLinkedList) {
// Check if the object's name matches the criteria, in this case, the name
// of the object has to match "second"
if (obj.name.equals("second")) {
// If we are within this block, it means that we found the object that has
// its name set as "second".
return obj;
}
}
You could also make a method to make things more elegant
public YourClass findByName(String name) {
for(YourClass obj : yourLinkedList) {
if (obj.name.equals(name)) {
return obj;
}
}
return null;
}
And use it the following way
YourClass object = findByName("second");
The easiest way to do this would be to of course, iterate through each element in the collection, checking if it matched your filter condition, and selecting the matches found. However this gets tedious the more times you need to do it, and the more complex your filter condition is. I would recommend utilizing pre-existing libraries to get the task done efficiently. Here is an example using Google-Collections:
final List<SomeObj> listObjs = Arrays.asList(
new SomeObj("first", 2, 4), new SomeObj("second", 3, 6),
new SomeObj("third", 5, 8));
final Iterable<SomeObj> filtered = Iterables.filter(listObjs,
new Predicate<SomeObj>() {
#Override
public boolean apply(final SomeObj obj) {
return "second".equals(obj.getName());
}
});
for (final SomeObj obj : filtered) {
System.out.println(obj);
}
The code shown would select all objects in the list with a name property of "second". Obviously, the predicate doesn't have to be an anonymous inner class - if you needed to reuse it you would just break it out to a standalone class.
Here's another way to implement a Comparator (just in case it helps).
I find it's easier to understand if you implement the Comparator explicitly:
class PersonAgeComparator implements Comparator<Person> {
#Override
public int compare(Person p1, Person person2) {
return p1.getAge().compareTo(p2.getAge());
}
}
You might use the above like this:
Comparator ageComparator = new PersonAgeComparator();
List<Person> personList = // populate list somehow
Person fourYearOld = new Person();
fourYearOld.setAge(4);
for (Person p : personList) {
if (ageComparator.compare(fourYearOld, p) == 0) {
System.out.println(p.getName() + " is 4 years old");
}
}
This doesn't make much sense for this simple example.
It would be ideal if you had several complicated ways to compare people (by height, by adjusted income, by how many states they've lived in, etc...).
Take a look at the java.util.Comprator interface. You can write a method that iterates over a List and uses a comparator to find the one you are after.
Something like (not compiled):
for(final T value : list)
{
if(comparator.compare(value, desired) == 0)
{
// match
}
}
In your comparator you have it perform whatever comparison you want.
Here is a working example:
public class JavaApplication4
{
public static void main(String[] args)
{
final List<Data> list;
final List<Data> a;
final List<Data> b;
list = new ArrayList<Data>();
list.add(new Data("Foo", 1));
list.add(new Data("Bar", 10));
list.add(new Data("Car", 10));
a = find(list,
new Data("Bar", 0),
new Comparator<Data>()
{
#Override
public int compare(final Data o1,
final Data o2)
{
return (o1.name.compareTo(o2.name));
}
});
b = find(list,
new Data(null, 10),
new Comparator<Data>()
{
#Override
public int compare(final Data o1,
final Data o2)
{
return (o1.count - o2.count);
}
});
System.out.println(a.size());
System.out.println(b.size());
}
private static List<Data> find(final List<Data> list,
final Data desired,
final Comparator<Data> comprator)
{
final List<Data> results;
results = new ArrayList(list.size());
for(final Data data : list)
{
if(comprator.compare(desired, data) == 0)
{
results.add(data);
}
}
return (results);
}
private static class Data
{
private final String name;
private final int count;
Data(final String nm,
final int c)
{
name = nm;
count = c;
}
}
}
And here is a generic version of the find method. Using this method you would never have to write the find method again, using a method that embeds the logic for matching in the iteration code means that you would have to re-write the iteration logic for each new set of matching logic.
private static <T> List<T> find(final List<T> list,
final T desired,
final Comparator<T> comprator)
{
final List<T> results;
results = new ArrayList(list.size());
for(final T value : list)
{
if(comprator.compare(desired, value) == 0)
{
results.add(value);
}
}
return (results);
}
You can go through it and get it done or there's another way.
You need to override the equals method in your class (and the hashcode method as well).
After you override the equals to your desire, in this case to compare the names, create a new object with the same name and call the remove(Object o) method of the LinkedList and get the object.
You should note that with this approach you objects equality will be defined by name and that the entry will be removed from the LinkedList
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);
List alma = new ArrayList();
alma.add(new Object[] { "alma", "korte" });
alma.add(new Object[] { "alma2", "korte2" });
alma.add(new Object[] { "alma3", "korte3" });
JXPathContext context = JXPathContext.newContext(alma);
List result = context.selectNodes("????????");
System.out.println(result);
So basically what should I write into the place of question marks to see the following output:
[alma,alma2,alma3]
I don't think it's possible. You need to put your data in some sort of container object. For example,
public class AlmaContainer {
List<AlmaObject> alma = new ArrayList<AlmaObject>();
}
public class AlmaObject {
String name;
String value;
AlmaObject(name, value) {
this.name=name
this.value= value
}
}
And then you can use the following expression:
context.selectNodes("alma/#name");
That's weird, but if you can't change your initial structure you can do it in 2 steps:
Iterator<Object> iter = context.iterate(".");
while(iter.hasNext()){
Object o=iter.next();
JXPathContext context2 = JXPathContext.newContext(o);
System.out.println(context2.getValue(".[1]"));
}
Outputs:
alma
alma2
alma3