Java.util.Arrays.sort for Vector

I used the java.util.Arrays.sort to sort an array based on the method below.
              java.util.Arrays.sort(array, 0, total, new ComparatorX());
           repaint();
            class ComparatorX implements java.util.Comparator
          public int compare( Object p1, Object p2){
               int x1=((Point)p1).x;
               int x2=((Point)p2).x;
               if(x1>x2)
                            return 1;
               if(x1>x2)
                            return -1;
               return 0;
     }I've since changed the array to a vector. Is there anyway I can keep the comparator. Or how can I sort the vector based on the above method.

BTW: Don't know if it's just a typing mistake, but your code contains an error:
class ComparatorX implements java.util.Comparator     {
   public int compare( Object p1, Object p2) {
      int x1=((Point)p1).x;
      int x2=((Point)p2).x;
      if (x1>x2) {
         return 1;
      if (x1>x2) {  // Should be: if (x2 > x1) ...
         return -1;
      return 0;

Similar Messages

  • Java.util.Array

    Exception in thread "main" java.lang.ClassCastException: Card
    at java.util.Arrays.mergeSort(Arrays.java:1044)
    at java.util.Arrays.sort(Arrays.java:997)
    at CardPlayer.sortHand(CardPlayer.java:91)
    at Game.main(Game.java:75)
    i get this error message after I call a sort method using the java.util.Array
    does anyone know why, or do u need more code?
    thanks

    The Card object needs to implement the Comparable interface if an array of them is to be sorted. The ClassCastException occurs when the sorting code attempts to assign a Card Object to a Comparable variable. The API documentation refers to this problem like this:
    Throws:
    ClassCastException - if the array contains elements that are not mutually comparable (for example, strings and integers).

  • How to set property "java.util.Arrays.useLegacyMergeSort" in jnlp-file?

    Hi,
    I have a problem in a web start application with java 7 and the new sort behavior (exception: comparison method violates its general contract).
    So I like to go back to previous behavior and tried to put the new java 7 system property "java.util.Arrays.useLegacyMergeSort" in the generated jnlp-File:
    <property name="java.util.Arrays.useLegacyMergeSort" value="true"/>.
    Now I can read the property value in java code with System.getProperty("java.util.Arrays.useLegacyMergeSort"), and guess the property was successful set, but the exception still appears?!
    The system property works with command line "javaws -J-Djava.util.Arrays.useLegacyMergeSort=true file.jnlp", but not via doubleclick on the jnlp-file or url and browser.
    Any ideas?
    Cheers,
    Dan

    Only "trusted" set of properties can be set in the JNLP file by unsigned applications.
    List of properties is revised from time to time but it usually takes time for new properties to be added to it (if there is strong demand for it as every property should undergo security audit).
    You can specify arbitrary property if you sign your application and JNLP file.

  • Using java.util.Arrays.binarySearch

    Hi,
    I tried the following code
    import java.util.Arrays ;
    class SecondTry {   
    public static void main(java.lang.String args[]) {
    int xyz[] = new int[10];
    xyz[0] = 5;
    xyz[1] = 6;
    xyz[2] = 1;
    Arrays.sort(xyz);
    System.out.println(Arrays.binarySearch(xyz,5));
    i expected to see a result of 1. But i get a 8.
    I am sure i must be doing something wrong. But not able to figure out what exactly is wrong. Could somebody help?
    TIA,
    Babu

    hi there,
    .The output was 8 because u have declared the array size to be 10,so the values which are not assigned would be assigned to zero,so if you change the array size to 3,u would get the desired output :)
    cheers
    class SecondTry {
    public static void main(java.lang.String args[]) {
    int xyz[] = new int[3]; //change to three
    xyz[0] = 5;
    xyz[1] = 6;
    xyz[2] = 1;
    Arrays.sort(xyz);
    System.out.println(Arrays.binarySearch(xyz,5));

  • Trouble extending java.util.Arrays

    I have written some utility functions for dealing with arrays and I would like to bundle them into a class along with java's built-in array functions (java.util.Arrays). To do this, I tried to extends the class java.util.Arrays like this:
    public class ArrayUtils extends java.util.Arrays
    /* some static methods */
    When I try to compile this with javac (even with no class body between the braces), I get an error "error:Cannot find constructor "Arrays" with matching parameters [JLS 15.12]". Does anyone know what's going on here? Why is the compiler looking for a constructor? And why can't it find one? I would very much appreciate your insight. Thanks. Eli

    Does anyone know what's
    going on here? Why is the compiler looking for a
    constructor? And why can't it find one?Conceputually....
    Inheritance exists to allow one to inherit from an object. In java objects can be created by using a class. However classes in java do not have to be objects. And you are trying to inherit from something that is not an object.
    One of the other uses for class in java is to group a number of convienent functions together. (Grouped functions do NOT represent a class.) That is what java.util.Arrays is.
    Technically....
    The class java.util.Arrays has a private constructor which means you can't derive anything from it.

  • TreeSet vs Collection.Sort / Array.sort for Strings

    Gurus
    I am pondering weather to use TreeSet vs the Collections.sort / Array.sort for sorting Strings.
    Basically I have a list of Strings, i need to perform the following operations on these Strings
    1) Able to list Strings starting with a Prefix
    2) Able to list Strings Lexically greater than a String
    Any help would be greatly appreciated!
    Thanks a bunch

    SpaceShuttle wrote:
    Gurus
    I am pondering weather to use TreeSet vs the Collections.sort / Array.sort for sorting Strings.
    Basically I have a list of Strings, i need to perform the following operations on these Strings
    1) Able to list Strings starting with a Prefix
    2) Able to list Strings Lexically greater than a String
    Any help would be greatly appreciated!
    Thanks a bunchBig-O wise, there's no difference between sorting a list of N elements or inserting them one by one in a tree-set. Both take O(n*log(n)). But both collections are not well suited for looking up string that start with a certain substring. In that case you had better use a Patricia tree (or Radix tree).
    Good luck.

  • Private static ArrayList within java.util.Arrays

    I was recently reviewing the code in java.util.Arrays (class version 1.45 - Java version 1.4.1). Beginning on line 2289 is a private static class named ArrayList. I'm completely baffled as to why the author created this slimmed-down private class (which would be, incidentally, returned by the Arrays.asList(Object[] a) method) rather than use the public class java.util.ArrayList. Can anyone offer an explanation?
    Thanks,
    John

    from JDK JAVADoc:
    asList
    public static List asList(Object[] a)
    Returns a fixed-size list backed by the specified array. (Changes to the returned list "write through" to the array.) This method acts as bridge between array-based and collection-based APIs, in combination with Collection.toArray. The returned list is serializable.
    So the private ArrayList extends java.util.ArrayList, and any changes made this list does not affect the internal Object[].... in other words can not be changed.

  • Java.util.Arrays; (method sort( ) )

    1) How to change a direction of sorting (on increase / on decrease)?
    2) Whether exists in java 2 something similar for sorting Strings ?

    1) How to change a direction of sorting (on increase
    / on decrease)?[url http://java.sun.com/j2se/1.5.0/docs/api/java/util/Collections.html#reverseOrder()]http://java.sun.com/j2se/1.5.0/docs/api/java/util/Collections.html#reverseOrder()
    2) Whether exists in java 2 something similar for
    sorting Strings ?Arrays.sort and Collections.sort will both sort the array or list as long as the type implements Comparable (or you supply a separate Comparator). Since String implements Comparable, those sort methods will sort the array or list of strings.
    Making Java Objects Comparable
    http://java.sun.com/docs/books/tutorial/collections/interfaces/order.html
    http://www.javaworld.com/javaworld/jw-12-2002/jw-1227-sort.html

  • AsList(java.lang.Object[]) in java.util.Arrays cannot be applied to (int[])

    hi all,
    i'm getting the above error msg when trying to compile a simple array prog...
    while at it, is there another simple way to print the contents
    of an array to the console in a single statement except using the asList method??? .. like :
    int[] myArray = {1,2,3,4};
    System.out.println(myArray);
    ==================================
    here's the code for my program :-
    tks in advance.
    import java.util.*;
    public class ListArray {
    public static void main(String args[]) {
         int[] anArray = {2,7,5,8,3};
         for (int i = 0; i < anArray.length; i++) {
         System.out.println("Element No : " + (i+1) + " = " + anArray);
         System.out.println("All the Elements : " + Arrays.asList(anArray));

    Funnily enough, thats because int[] is not an array of Objects.
    You can make your listing method work by writing this instead:
    for (int index = 0; index < anArray.length; index++) {
      System.out.println("Element No: " + (index + 1) + " = " + anArray[index]);
    }

  • Error: java.lang.ClassCastException: java.util.Arrays$ArrayList

    Hi,
    How to solve this error?
    I get the error at this line of code in my program.
    java.util.ArrayList list= (java.util.ArrayList)obj;
    Please help how to solve this problem.
    Thanks,
    cmbl

    cmbl wrote:
    How to solve this error?
    I get the error at this line of code in my program.
    java.util.ArrayList list= (java.util.ArrayList)obj; Don't do this cast.
    Why are you doing this cast anyway? I think you need to show a small bit of compilable code (or almost compilable except perhaps for this error) and some more explanation.

  • Zip (java.util.zip) implementation for Java ME

    As part of the UrbanWeb project at the Aarhus University in Denmark, the Java util.zip package has been ported to the Java Microedition (Java JME) platform. The porting was based on the GNU Classpath implementation. To avoid future conflicts and name clashes, the package was moved to gnu.classpath.
    The package is released under the original license and is freely available for all mobile Java developers.
    Please visit the project page for more information about the zip utilities (util.zip) for the Java JME platform:
    [http://www.interactivespaces.net/projects/project.php?projectId=49&mode=prototypes|http://www.interactivespaces.net/projects/project.php?projectId=49&mode=prototypes]
    Best regards, Allan Hansen

    We have simple applied the original license. See http://www.gnu.org/software/classpath/license.html
    Classpath is distributed under the terms of the GNU General Public License with the following clarification and special exception.
    Linking this library statically or dynamically with other modules is making a combined work based on this library. Thus, the terms and conditions of the GNU General Public License cover the whole combination.
    As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules, and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version.
    As such, it can be used to run, create and distribute a large class of applications and applets. When GNU Classpath is used unmodified as the core class library for a virtual machine, compiler for the java languge, or for a program written in the java programming language it does not affect the licensing for distributing those programs directly.
    Best regards, Allan Hansen

  • Compile error when using Collections.sort for Vector, why?

    The compiler is giving an error when trying to do this (I'm using JDK 1.5.0_09):
    Vector <String> test = new Vector <String>();
    test.add("test1");
    test.add("test2");
    test.add("test3");
    Collections.sort(test);The error being:
    The method sort(Vector<String>) is undefined for the type Collections
    Collections.sort takes List, but Vector is of type List, so this should work, correct?

    ChuckBing wrote:
    No. Vector is not a subclass of List. Use List.um.. Vector implements List

  • Sort a vector of objects by one of its attributes

    Hi all!
    I have created this class:
    public class Client {
    private int numero;
    private double tempsEntrada;
    private double tempsServei;
    private double tempsIniciSessio;
    private char tipus;
    * Creates a new instance of Client
    public Client(int num, double temp,double servei, char tip) {
    numero = num;
    arrivalTime = temp;
    serviceTime = servei;
    tipus = tip;
    public char getTipus()
    return tipus;
    public int getNumero()
    return numero;
    public double getTempsEntrada()
    return arrivalTime;
    public double getTempsServei()
    return serviceTime;
    Now I've done a java vector of this object, and I want to sort it by arrivalTime.
    The class comparer looks like this
    public class Comparer implements Comparator {
    public int compare(Object obj1, Object obj2)
    double temps1 = ((Client)obj1).getTempsEntrada();
    double temps2 = ((Client)obj2).getTempsEntrada();
    return (int)(temps1 - temps2);
    now when I do Collections.sort(vector);
    this is the error reported:
    Exception in thread "main" java.lang.ClassCastException: cafevirtual.Client cannot be cast to java.lang.Comparable
    at java.util.Arrays.mergeSort(Arrays.java:1144)
    at java.util.Arrays.mergeSort(Arrays.java:1155)
    at java.util.Arrays.mergeSort(Arrays.java:1155)
    at java.util.Arrays.sort(Arrays.java:1079)
    at java.util.Collections.sort(Collections.java:117)
    at cafevirtual.Main.main(Main.java:76)
    Java Result: 1
    what's wrong?
    thanks!

    Your Client class does not implement Comparable. You have to specify the Comparator to use: Collections.sort(vector, new Comparer());

  • Arrays.sort

    Why is the Arrays.sort method defined as
    public static void sort(Object[] a)
    instead of
    public static void sort(Comparable[] a) ?

    jverd wrote:
    This way we can sort an array whose elements are all mutually comparable, even if the array itself is not declared to be of a Comparable type. I can't think of a specific use case where that would be useful, but it's the only reason I can think of for deliberately making that decision.Dear jverd, I am not sure I understand the possible case you are referring to. I tried the following code and it gives a runtime Exception.
      public class ArraysTest {
        public static void main(String argsp[]){
            Data [] dr = new Data[4];
            dr[0] = new Data(4);        dr[1] = new Data(0);
            dr[2] = new Data(8);        dr[3] = new Data(3);
            Arrays.sort(dr);
            System.out.println(dr);
    class Data{
        Integer i;
        public Data(int j){
            i = j;
        public int compareTo(Data d){
            if(i<d.i)
                return -1;
            if(i==d.i)
                return 0;
            return 1;
        @Override
        public String toString(){
            return i.toString();
    }<font color="red">
    Exception in thread "main" java.lang.ClassCastException: temp.Data cannot be cast to java.lang.Comparable
    [Ltemp.Data;@b37c60d
    at java.util.Arrays.mergeSort(Arrays.java:1144)
    at java.util.Arrays.sort(Arrays.java:1079)
    </font>

  • Multidimensional Array Sort

    Please help. I am very new to java and trying to build a multidimensional array. I have two variables 1)item_name and 2)item_value. These are values that I obtain by looping through a database result set. I need to build and array that can hold these variables. Once the multidimensional array is built I need to be able to sort it by item value.
    For example I would like to do something like this:
    while (rs.next)
    array.name = item_name
    array.value = item_value
    end
    array.sort(value)
    Thanks for any help!

    Don't use a multidimensional array. Use an array of objects, where the objects are of a class that you define. It might be something as simple as class Item that just has two fields--name and value--and their getters and setters. Or maybe just getters if you want the class to be immutable.
    Have the class implement Comparable and sort on value.
    If you sometimes want to sort on value and sometimes on name, then you'll need to either define two Comparators (one for name, one for value) or make the class Comparable on whichever is the more "natural" ordering and define a Comparator for the other one.
    Either put them in an array and use one of the java.util.Arrays.sort methods to sort them, or put them in a List (java.util.LinkedList or java.util.ArrayList) and use Collections.sort to sort them.

Maybe you are looking for

  • How do I locate my thumb drive in from the "look in" drop down?

    I'm trying to open a document from my thumb drive.  However, when I select the "look in" drop down it's not listed.  It's listed under the finder as a device and I can see the document from there.  However, because I don't have this software to open

  • GT70 graphics card

    Hello, where can i find the gtx 770m drivers? I looked up my laptop in the msi website and the graphics driver that they have is for the 680m. Can someone post a link to the official drivers. Thank you

  • File´s wont open after re-installing FCP

    Hello, I have just re-installed Final Cut Studio 2 after the hard drive was replaced. When trying to open files that were made over the last couple of years with this very version, about 44% is read and then this message appears -  ´File´s format is

  • Best practice to change IP?

    Hi everyone, I need to use VPN to connect to another network. The problem is that this network uses the same IP range as mine (10.0.1.x). I know that this is a problem and should be avoided, especially since the respective network's servers even have

  • Cisco 1572 Outdoor AP in Autonomous or Site Survey mode?

    Can a 1572 outdoor AP be put into an Autonomous mode, or at least a Site Survey mode so coverage areas and signal strengths can be tested without the need for a wireless controller? If so, is that what the sku "SW1570-UL01A01-K9   SW Cisco AP1570: Un