How to sort an array of objects?
I need to sort an array of objects. Each object has serial number, and other properties. I need to sort it by serial number.
Do a java.util.Arrays.sort(). The method has quite a few overloads, so I'll give a complete example this time:import java.util.*
public class SortDemo {
public static void main(String args) {
SimpleObject[] objs = new SimpleObject[10];
for (int i=0; i<10; i++)
objs=new SimpleObject();
dump(objs);
Comparator c = new SimpleComparator();
Arrays.sort(objs, c);
dump(objs);
static void dump(Object[] o) {
for (int i=0; i<o.length; i++)
System.out.print(o[i] + " ");
/** Object to demonstrate comparing with **/
class SimpleObject {
private int n = (int) (10*Math.random());
public String toString() {
return String.valueOf(getNumber());
public int getNumber() {return n;}
/** The custom comparator **/
class SimpleComparator implements Comparator {
public int compare(Object o1, Object o2) {
return ((SimpleObject) o1).getNumber() - ((SimpleObject) o2).getNumber();
public boolean equals(Object o) {return false;}
}I could have made the SimpleObject class "Comparable", but a design like this allows more flexibility so I decided to use another class for the Comparator.
Similar Messages
-
hi there, i have to sort an array of object that looks like:
surname, name, age, height
well i have to sort them alphabetically like this:
based on the surnames, if the surnames are the same than sort on the base of the names; if the names are the same sort them on the base of age and so on. If all the fields are the same the order is non important.
Well I am not sure how I can do it using the Comparable Interface? as it is an interface i don't have any idea how to implement itThis search took 2 seconds to do. And it's using your exact subject header. Next time try searching, instead of waiting forever hoping that someone will help you.
http://search.java.sun.com/search/java/index.jsp?col=javaforums&qp=&qt=%2B%22sorting+an+array+of+objects%22 -
How to list an array of objects using struts in jsp and ActionForm
I am using the struts ActionForm and need to know how to display an Array of objects. I am assuming it would look like this in the ActionForm:
private AddRmvParts addRmv[];
But I am not sure how the getter and setter in the ActionForm should look. Should it be a Collection or an Iterator?
I am thinking I need to use an iterator in the jsp page to display it.
I am also wondering if the AddRmvParts class I have can be the same class that gets populated by the retrieval of data from the database. This class has 10 fields that need to display on the jsp page in 1 row and then multiple rows of these 10 fields.
Thanks.Most probably the easiest way to make it accessible in your page is as a collection.
ie
public Collection getAddRmvParts()
You can use the <logic:iterate> or a <c:forEach>(JSTL) tag to loop through the collection
As long as the individual items in the collection provide get/set methods you can access them with the dot syntax:
Example using JSTL:
<c:forEach var="addRmvPart" items="${addRmvParts}">
<c:out value="${addRmvPart.id} ${addRmvPart.name} ${addRmvPart.description}"/>
</c:forEach> -
Sorting an array of Objects based on a variable inside each object
I have a class public class handInfo
//VARS
int highC = 0;
int hVal = 0;
int numHand = 0;
//CONSTRUCOTRS
public handInfo()
//METHODS
public void setHC(int hc)
highC = hc;
public void setHV(int hv)
hVal = hv;
public void setNH(int nh)
numHand = nh;
public int getHC()
return highC;
public int getHV()
return hVal;
public int getNH()
return numHand;
}now i have an array, handInfo[] hands = new handInfo[4];
hands[0] = new handInfo();
hands[0].setHC(HV);
hands[0].setNH(1);
hands[0].setHV(Val);
hands[1] = new handInfo();
hands[1].setHC(HV2);
hands[1].setNH(2);
hands[1].setHV(Val2);
hands[2] = new handInfo();
hands[2].setHC(HV3);
hands[2].setNH(3);
hands[2].setHV(Val3);
hands[3] = new handInfo();
hands[3].setHC(HV4);
hands[3].setNH(4);
hands[3].setHV(Val4);i need to know how to sort this array, based off hVal...
D:Write a Comparator and call Arrays.sort(array, Comparator).
-
Java sorting the array of objects
Hi ,
I have a question on sorting objects in java.
I have a java interface some thing like :
public classmyObj extends Nullable
private int objId;
private Datemydate;
public int getObjID();
public Date getmyDate();
public int getISecondD();
}I need to create the array of the objects of this class that are sorted on the ObjID:
classmyObj[] collectionObjects
I need to pass this collectionObjects to another function.
Now how should I sort these objects based on the ObjID on collection?
Please help with this!
Thanksneeto wrote:
Hi ,
I have a question on sorting objects in java.
I have a java interface some thing like :You mean class?
>
public classmyObj extends Nullable
private int objId;
private Datemydate;
public int getObjID();
public Date getmyDate();
public int getISecondD();
}I need to create the array of the objects of this class that are sorted on the ObjID:
classmyObj[] collectionObjects
I need to pass this collectionObjects to another function.
Now how should I sort these objects based on the ObjID on collection?Create a comparator and use it in a call to Collections.sort (or Arrays.sort if you have an array) -
Sorting an array of objects and returning another variable
Hi there,
Bit stuck on this one I wonder if anyone can help..
I have an object array into which I've pushed a number of objects with different variables :-
myArray.push({myRef: 1, myValue: "W"});
I can sort the array in numerical order using :-
myArray.sortOn("myRef", Array.NUMERIC);
but after sorting I would like to collapse the array using something along the lines of :-
myArray.join("");
to join the OTHER variable (myValue)...
Is it possible to do this without pushing every instance of 'myValue' to another array and then joining that ?
Many Thanks in advance
MartinHi kglad,
I really appreciate you helping, but I have had to completely change my approach to this problem, therefore I will be marking the question as answered !!
Thanks again -
Sorting an array of objects by an attribute
I'm pretty new to java so don't laugh if you think my question is real easy!
I have an array of objects and I want to sort them according to an integer value stored in each object. Any help would be very much appreciated.
Thanks for looking!!Perhaps an example would help:
public class Person {
private String name;
private int age;
public void setName(String name) { this.name = name; }
public void setAge(int age) { this.age = age; }
public String getName() { return name; }
public int getAge() { return age; }
=====
public class PersonAgeSorter implements Comparable {
public int compare(Object o1, Object o2) {
Person p1 = (Person) o1;
Person p2 = (Person) o2;
Integer i1 = new Integer(p1.getAge());
Integer i2 = new Integer(p2.getAge());
return i1.compareTo(i2);
=====
public class PersonNameSorter implements Comparable {
public int compare(Object o1, Object o2) {
Person p1 = (Person) o1;
Person p2 = (Person) o2;
String s1 = p1.getName();
String s2 = p2.getName();
return s1.compareTo(s2);
=====
import java.util.Arrays;
public class SortExample {
public static void main(String [] args) {
Person p1 = new Person();
Person p2 = new Person();
p1.setName("Tom");
p1.setAge(22);
p2.setName("Nancy");
p2.setAge(33);
Person [] people = new Person[2];
people[0] = p1;
people[1] = p2;
Arrays.sort(people, new PersonAgeSorter());
Arrays.sort(people, new PersonNameSorter());
} -
Please tell me how can declare an array of object.
how to create a two dimentional array object of a class.
let,
class abc{
abc(){
is it posible--
abc ss=new abc[10][10]
please tell me how can declare an array object.then always use String and don't consider
StringBuffer at the outset. 'best practices' need not
be seen as premature optimization. besides, if it is
abstracted, does not matter how it is stored
internallyNot sure I would agree with this example - a String is immutable, if I want to change the object then using a StringBuffer makes sense (conveys the intend, yada, yada, yada).
Although, I do agree with you that some optimizations are best practices and should be used. I also come from the old days when optimization was always on our mind. Also, I would not expect someone to do something like re-calculate a value every time it is needed instead of storing the value in a variable, just to avoid optimization.
I just think that the example of using a 1-dimensional array when a 2-dimentional array is a better representaion of the "real world" will both obscure the intention and compicate the code. -
Help sorting an array of objects needed please.
I am trying to sort the array Students[] in descending order of Fees due. Using the code below I get a null pointer error at runtime. The array is not completely full, it has 20 cells, but the variable studentArrayCounter holds the number of used cells. The 'getFeesDue()' code returns an integer value.
Any help is appreciated.
// Sort Student Records Method
public void sortStudentRecords()
int loopCount = 0;
for (loopCount = 1; loopCount < studentArrayCounter; loopCount ++)
if(Students[loopCount].getFeesDue()>Students[loopCount-1].getFeesDue())
SortStudents[0]=Students[loopCount-1];
Students[loopCount-1]=Students[loopCount];
Students[loopCount]=SortStudents[0];
}Also, unless the excersize is to write a sort algorigthm (which I kinda doubt) you should use Arrays.sort
Arrays.sort(Students, new Comparator() {
public int compare(Object o1, Object o2) {
Student s1 = (Student) o1;
Student s2 = (Student) o2;
return s1.getFeesDue() - s2.getFeesDue();
}); -
How to sort StringBuffer array?
I got a little problem regarding sorting a StringBuffer Array. As you all know arithmetic operation can't be perform on StringBuffer. So do I have any other alternative on sorting it? I try ".toString()" function but can't use also.
Your talking about sorting the characters in a StringBuffer object, and not sorting an array of StringBuffers right? Well, isnt a StringBuffer basically a character array? If you use the getChars function, you can copy the StringBuffer into a character array, and from there use a bubble or quicksort to sort the characters...?
-
How to pass a array of object to oracle procedure using callable
Hi,
I am calling a oracle stored procedure using callable statement which has IN and OUT parameter of same type.
IN and OUT are array of objects. (ie) IN parameter as Array of Objects and OUT parameter as Array of Objects
here are the steps i have done as advised from oracle forum. correct me if i am in wrong direction
ORACLE types and Stored Procedure
CREATE OR REPLACE
TYPE APPS.DEPARTMENT_TYPE AS OBJECT (
DNO NUMBER (10),
NAME VARCHAR2 (50),
LOCATION VARCHAR2 (50)
CREATE OR REPLACE
TYPE APPS.DEPT_ARRAY AS TABLE OF department_type;
CREATE OR REPLACE package body APPS.insert_object
IS
PROCEDURE insert_object_prc (d IN dept_array, d2 OUT dept_array)
IS
BEGIN
d2 := dept_array ();
FOR j IN 1 .. d.COUNT
LOOP
d2.EXTEND;
d2 (j) := department_type (d (j).dno, d (j).name, d(j).location);
END LOOP;
END insert_object_prc;
END insert_object;
JAVA CODE
Value Object
package com.custom.vo;
public class Dep {
public int empNo;
public String depName;
public String location;
public int getEmpNo() {
return empNo;
public void setEmpNo(int empNo) {
this.empNo = empNo;
public String getDepName() {
return depName;
public void setDepName(String depName) {
this.depName = depName;
public String getLocation() {
return location;
public void setLocation(String location) {
this.location = location;
to call stored procedure
package com.custom.callable;
import com.custom.vo.Dep;
import oracle.jdbc.OracleCallableStatement;
import oracle.jdbc.OracleConnection;
import oracle.jdbc.OracleTypes;
import oracle.jdbc.pool.OracleDataSource;
import oracle.sql.ARRAY;
import oracle.sql.ArrayDescriptor;
import oracle.sql.Datum;
import oracle.sql.STRUCT;
import oracle.sql.StructDescriptor;
public class CallableArrayTryOut {
private static OracleDataSource odcDataSource = null;
public static void main(String[] args) {
OracleCallableStatement callStatement = null;
OracleConnection connection = null;
try {
odcDataSource = new OracleDataSource();
odcDataSource
.setURL("......");
odcDataSource.setUser("....");
odcDataSource.setPassword("....");
connection = (OracleConnection) odcDataSource.getConnection();
} catch (Exception e) {
System.out.println("DB connection Exception");
e.printStackTrace();
Dep[] dep = new Dep[2];
dep[0] = new Dep();
dep[0].setEmpNo(100);
dep[0].setDepName("aaa");
dep[0].setLocation("xxx");
dep[1] = new Dep();
dep[1].setEmpNo(200);
dep[1].setDepName("bbb");
dep[1].setLocation("yyy");
try {
StructDescriptor structDescriptor = new StructDescriptor(
"APPS.DEPARTMENT_TYPE", connection);
STRUCT priceStruct = new STRUCT(structDescriptor, connection, dep);
STRUCT[] priceArray = { priceStruct };
ArrayDescriptor arrayDescriptor = ArrayDescriptor.createDescriptor(
"APPS.DEPT_ARRAY", connection);
ARRAY array = new ARRAY(arrayDescriptor, connection, priceArray);
callStatement = (OracleCallableStatement) connection
.prepareCall("{call insert_object.insert_object_prc(?,?)}");
((OracleCallableStatement) callStatement).setArray(1, array);
callStatement.registerOutParameter(2, OracleTypes.ARRAY,
"APPS.DEPT_ARRAY");
callStatement.execute();
ARRAY outArray = callStatement.getARRAY(2);
Datum[] datum = outArray.getOracleArray();
for (int i = 0; i < datum.length; i++) {
oracle.sql.STRUCT os = (oracle.sql.STRUCT) datum[0];
Object[] a = os.getAttributes();
for (int j = 0; j < a.length; j++) {
System.out.print("Java Data Type :"
+ a[j].getClass().getName() + "Value :" + a[j]
+ "\n");
connection.commit();
callStatement.close();
} catch (Exception e) {
System.out.println("Mapping Error");
e.printStackTrace();
THE ERROR
Mapping Errorjava.sql.SQLException: Inconsistent java and sql object types
at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:134)
at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:179)
at oracle.jdbc.dbaccess.DBError.check_error(DBError.java:1130)
at oracle.sql.StructDescriptor.toOracleArray(StructDescriptor.java:823)
at oracle.sql.StructDescriptor.toArray(StructDescriptor.java:1735)
at oracle.sql.STRUCT.<init>(STRUCT.java:136)
at com.custom.callable.CallableArrayTryOut.main(CallableArrayTryOut.java:48)You posted this question in the wrong forum section. There is one dedicated to Java that was more appropriate.
Anyway here is a link that describes what you should do.
http://download.oracle.com/docs/cd/B19306_01/java.102/b14355/oraarr.htm#i1049179
Bye Alessandro -
Re: how to sort an array of type string
thanks bina and turing pest. well i can't use collections.sort or arrays.sort i need to create a method to sort. stupid instructor dont want to take advantage of this good java language. anyways i am able to do the sort but now OMG the whole data is crappy. formatting is gone everything is fukedd up. excuse my language.
public void getSort(String[] A)
String temp= A[0];
for(int i=0; i<A.length; i++)
for (int j=0; j<A.length-1-i; j++)
if(A[j].compareTo(A[j+1])>0)
temp = A[j];
A[j] = A[j+1];
A[j+1] = temp;
}and here is my output if i dont use the sort before it was not giving me an exception of arraysoutofbound and now it is
Item Number Cost_unit Sale_unit TotalSale profit Totalprofit
Binder 500 4 7 3300 1500 1500
Bookbag 350 5 10 3300 1750 3250
Calendar 300 3 8 2400 1500 4750
Shirt 800 4 6 4600 1600 6350
Notebook 400 1 2 800 400 6750
Schedule 876 1 2 1752 876 7626and if i turn my sort function on this is what i getg
Item Number Cost_unit Sale_unit TotalSale profit Totalprofit
4 500 7 Binder 3300 1500 1500
10 350 5 Bookbag 3300 1750 3250
3 300 8 Calendar 2400 1500 4750
4 6 800 Shirt 4600 1600 6350
1 2 400 Notebook 800 400 6750
1 2 876 Schedule 1752 876 7626
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at BookStore.main(BookStore.java:62)at this line it is giving me an exception
totalsale = test.totalSales(Integer.parseInt(str[1].trim()), Integer.parseInt(str[3].trim()));why is it all messed up?you create bean for your data like this
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
public String getName() {
return name;
public void setName(String name) {
this.name = name;
public int getAge() {
return age;
public void setAge(int age) {
this.age = age;
public String toString() {
return "Name : " + name + "\n" + "Age : " + age;
}after that, just sort it
public class Sample {
public static void main(String[] args) {
Person[] array = new Person[3];
array[0] = new Person("Dewi", 20);
array[1] = new Person("Agus", 21);
array[2] = new Person("Cindy", 18);
sortByName(array);
printOut(array);
private static void printOut(Person[] array) {
for(Person person : array){
System.out.println(person);
System.out.println();
private static void sortByName(Person[] array) {
for (int i = 0; i < array.length; i++) {
for (int j = array.length - 1; j > i; j--) {
if (array[j].getName().compareTo(array[j - 1].getName()) < 0) {
Person temp = new Person(array[j].getName(), array[j].getAge());
array[j].setName(array[j - 1].getName());
array[j].setAge(array[j - 1].getAge());
array[j - 1].setName(temp.getName());
array[j - 1].setAge(temp.getAge());
} -
How to initialize the array with object?
Here is type I have.
CREATE OR REPLACE TYPE SYSADM.AP_COMMENT_TYPE AS OBJECT
BU_AP VARCHAR2(5),
VOUCHER VARCHAR2(10),
V_LINE INTEGER,
USERID VARCHAR2(20),
COMMENT_DTTM DATE,
COMMENT VARCHAR2(254)
CREATE OR REPLACE TYPE SYSADM.AP_COMMENT_COLL AS VARRAY(1000) OF SYSADM.AP_COMMENT_TYPE;
Then I created a procedure to grab some data.
PROCEDURE get_voucher_comments (
v_bu_in IN VARCHAR2,
v_voucher_in IN VARCHAR2,
v_line_in IN NUMBER,
v_userid IN VARCHAR2,
voucher_comment OUT sysadm.ap_comment_coll
IS
i NUMBER := 1;
v_comments VARCHAR2 (254) := ' ';
comment_type sysadm.ap_comment_type;
v_line_num NUMBER := 0;
CURSOR get_all_comment
IS
SELECT voucher_line_num, descr254_mixed
FROM ps_fas_ap_comment
WHERE business_unit = voucher_comment (i).bu_ap
AND voucher_id = voucher_comment (i).voucher;
CURSOR get_line_comment
IS
SELECT descr254_mixed
FROM ps_fas_ap_comment
WHERE business_unit = voucher_comment (i).bu_ap
AND voucher_id = voucher_comment (i).voucher
AND voucher_line_num = voucher_comment (i).v_line;
BEGIN
voucher_comment (1) := ap_comment_type (' ', ' ', 0, ' ', '', ' ');
--voucher_comment (1) := ap_comment_type (null, null, null, null, null,null);
IF voucher_comment (i).v_line = 0
THEN
OPEN get_all_comment;
LOOP
FETCH get_all_comment
INTO v_line_num, v_comments;
voucher_comment.EXTEND;
voucher_comment (i) :=
ap_comment_type (v_bu_in,
v_voucher_in,
v_line_num,
v_userid,
TO_DATE (TO_CHAR (SYSDATE,
'DD-MON-YYYY HH24:MI:SS'
'DD-MON-YYYY HH24:MI:SS'
v_comments
i := i + 1;
END LOOP;
ELSE
OPEN get_line_comment;
LOOP
FETCH get_line_comment
INTO v_comments;
voucher_comment.EXTEND;
voucher_comment (i) :=
ap_comment_type (v_bu_in,
v_voucher_in,
v_line_num,
v_userid,
TO_DATE (TO_CHAR (SYSDATE,
'DD-MON-YYYY HH24:MI:SS'
'DD-MON-YYYY HH24:MI:SS'
v_comments
i := i + 1;
END LOOP;
END IF;
END get_voucher_comments;
But when I tried to test the procedure, got error: ORA-06531: Reference to uninitialized collection. Does anyone have experience of handling array with object?
declare
O_voucher_comment SYSADM.AP_COMMENT_COLL;
begin
FAS_AP_EXCEPTIONS.GET_VOUCHER_COMMENTS('FCCAN', '20494753', 1, 'KEHE', O_voucher_comment);
end;Thanks for that. I changed it a little bit, but when i ran this script, got ORA-06532: Subscript outside of limit.
declare
O_voucher_comment SYSADM.AP_COMMENT_COLL := sysadm.ap_comment_coll(null);
begin
FAS_AP_EXCEPTIONS.GET_VOUCHER_COMMENTS('FCCAN', '20494753', 0, 'KEHE', O_voucher_comment);
end;
PROCEDURE get_voucher_comments (
v_bu_in IN VARCHAR2,
v_voucher_in IN VARCHAR2,
v_line_in IN NUMBER,
v_userid IN VARCHAR2,
voucher_comment OUT sysadm.ap_comment_coll
IS
i NUMBER := 1;
v_comments VARCHAR2 (254) := ' ';
comment_type sysadm.ap_comment_type;
v_line_num NUMBER := 0;
CURSOR get_all_comment
IS
SELECT voucher_line_num, descr254_mixed FROM ps_fas_ap_comment
WHERE business_unit = v_bu_in AND voucher_id = v_voucher_in;
CURSOR get_line_comment
IS
SELECT descr254_mixed FROM ps_fas_ap_comment
WHERE business_unit = v_bu_in AND voucher_id = v_voucher_in
AND voucher_line_num = v_line_in;
BEGIN
--voucher_comment() := SYSADM.ap_comment_type (NULL, NULL, NULL, NULL, NULL, NULL);
--' ', ' ', 0, ' ', '', ' ' sysadm.ap_comment_coll
voucher_comment := sysadm.ap_comment_coll(null);
IF v_line_in = 0
THEN
OPEN get_all_comment;
LOOP
FETCH get_all_comment
INTO v_line_num, v_comments;
if i > 1
then
voucher_comment.EXTEND;
end if;
voucher_comment (i) := ap_comment_type (v_bu_in,
v_voucher_in, v_line_num, v_userid,
TO_DATE (TO_CHAR (SYSDATE, 'DD-MON-YYYY HH24:MI:SS'), 'DD-MON-YYYY HH24:MI:SS'), v_comments );
i := i + 1;
END LOOP;
ELSE
OPEN get_line_comment;
LOOP
FETCH get_line_comment
INTO v_comments;
voucher_comment.extend(6);
voucher_comment (i) := ap_comment_type (v_bu_in, v_voucher_in, v_line_num, v_userid, TO_DATE (TO_CHAR (SYSDATE, 'DD-MON-YYYY HH24:MI:SS' ), 'DD-MON-YYYY HH24:MI:SS'), v_comments);
i := i + 1;
END LOOP;
END IF;
END get_voucher_comments; -
How to sort a Array to be new Array in descend?
hello guys:
I have a array String[] selected = {0,1,2,3,4,5,6,7,8,9};I want to sort it into a new Array like : {9,8,7,6,5,4,3,2,1,0} , how i can do
thanksHmmmm not sure if you meant
int[] selected
rather than
String[] selected
You can't sort int[] in descending order using the standard API, you could though do a normal sort of the array and then iterate through it swapping element indexes, the first one in ascending sort will become the last one and the 2nd becomes the 2nd last one and so on....
for (int i=0;i<selected.length / 2;i++) {
int temp = selected;
selected[i] = selected[selected.length - i - 1];
selected[selected.length - i - 1] = temp; -
How to create an Array of Object
Is this correct:
Object[] anArray = new Object[5];
Thanks.Your code will create an array of 5 null references to class Object. After that line you could code:anArray[0] = new Integer(5);- or -
Object x = anArray[1];but if you code:anArray[3].DoSomething();and have not initialized anArray[3], you will get a NullPointerException.
Doug
Maybe you are looking for
-
Help! Can't edit tags, everything is grayed out.
Hey there. I've recently got a new laptop and my iTunes library is located on an external hard drive. When I try to edit a single song (via "Get Info") I cannot change anything, everything is grayed out. However, it allows me to change the informatio
-
Dear Experts , If i maintain BOM for a material , I can use the same when i procure the material through subcontracting where the components to be provided to the vendor are picl\ked from the BOM. But i need to use the same material in a standard ite
-
I keep getting this message- "An error occurred while trying to save your photo library." "Some recent changes may be lost. Make sure your hard disk has enough space and that iPhoto is able to access the iPhoto Library." It will not stop coming up ev
-
Hey guys i recently bought a new iPod 5.5G but I've been using iTunes for a while and when i synched it up it said i need iTunes 7.0 or later so i downloaded the latest iTunes but when i tried to install it it came up with an error: "The installation
-
Mail failing in new and amazing ways
Many questions here and many frustrations. Running 10.5.6 1: Starting yesterday whenever I open Mail my Gmail account downloads my recent mail just fine. But any time after that the spinning icon next to the account spins forever and it won't downloa