Comparing objects in arraylist

Guys!
I filled an arraylist with several objects that are moving. Now I want to check whether the objects are at the same position using a for loop. How can I do this best?

yep sorry about that
Here is my code:
import java.applet.*;
import java.awt.*;
import javax.swing.Timer;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.lang.Object;
import java.util.ArrayList;
import java.util.Random;
//een simpel schietspel van 15 seconden waarbij het ruimteschip dmv raketten bewegende aliens
//moet zien te raken en dmv bewegen zijn positie kan bepalen
public class Spel extends Applet
     //Timers
     Timer nieuwePositieTimer;
     Timer nieuweAlienTimer;
     Timer stopSpelTimer;
     //een nieuwe arraylist bewegendedelen
     ArrayList<BewegendeDelen> bewegendedelenarray = new ArrayList<BewegendeDelen>();
     Ruimteschip ruimteschip = new Ruimteschip();
    Raket raket = null;
     public void init()
          setBackground(Color.white);
          //nieuwepositielistener
          ActionListener nieuwePositieListener = new nieuwePositieListener();
          //interval van 1/4 seconde
          final int nieuwepositieDELAY = 250;
          //nieuwe positie timer
          Timer nieuwePositieTimer = new Timer(nieuwepositieDELAY, nieuwePositieListener);
        this.nieuwePositieTimer = nieuwePositieTimer;
          //start de nieuwe positietimer
          nieuwePositieTimer.start();
          //nieuwe alien listener
          ActionListener nieuweAlienListener = new nieuweAlienListener();
          //interval van 4 seconden
          final int nieuwealienDELAY = 4000;
          //nieuwe alientimer
          Timer nieuweAlienTimer = new Timer(nieuwealienDELAY, nieuweAlienListener);
        this.nieuweAlienTimer = nieuweAlienTimer;
          //start de nieuwe alientimer
          nieuweAlienTimer.start();
          //stop het spel listener
          ActionListener stopSpelListener = new stopSpelListener(15);
          //1 seconde interval
          final int stopspelDELAY = 1000;
          //nieuwe timer stop het spel
          stopSpelTimer = new Timer(stopspelDELAY, stopSpelListener);
          //start de timer
          stopSpelTimer.start();
          //bewegendedelenarray.add(alien);
          bewegendedelenarray.add(ruimteschip);
          //bewegendedelenarray.add(raket);
     //tekenen
     public void paint(Graphics g)
     {     //print uit bewegendedelenarray obj van het type BewegendeDelen
          for(BewegendeDelen obj : bewegendedelenarray)
          {     //teken de bewegende delen (ruimteschip, aliens en raketten)
               System.out.println(obj);
               obj.paint(g);
               //als teller op nul staat game over!
               if (count <= 0)
               g.drawString("Game over!", 250, 250);
               //laat de score zien als de teller op nul staat
               if (count <= 0)
               g.drawString("Je score is: " + score + "!", 250, 300);
     //pijltjes toetsen indrukken om te bewegen en spatie om te schieten
     public boolean keyDown(Event e, int key)
          {     //naar links
               if(key == Event.LEFT)
               {     if (ruimteschip.getX() > 10)
                         ruimteschip.beweegLinks();
                         System.out.println("links");
                         repaint();
               else
               //naar rechts
               if(key == Event.RIGHT)
               {     if (ruimteschip.getX() < 450)
                         ruimteschip.beweegRechts();
                         repaint();
               else
               //schieten
               if (key == 32)
                    raket = new Raket(ruimteschip.getX(), ruimteschip.getY());
                bewegendedelenarray.add(raket);
                    raket.beweeg();
                    repaint();
          return true;
     //kijken of de raket een alien raakt
     public boolean isGeraakt()
          for(BewegendeDelen obj : bewegendedelenarray)
          //controleren of er een raket is
          while(raket != null)
          {     //als objecten zelfde coordinaten hebben, verwijder object, opnieuw tekenen en score ophogen
               if (obj.getX() >= obj.getX()  && obj.getX() <= (obj.getX()+obj.getWeergave().length()) && obj.getX()==obj.getY())
               {     //roep verwijderen aan
                    obj.verwijder();
                    raket = null;     
                    repaint();
                    score++;
          return !gemist;
     //iedere 1/4 seconden krijgen de aliens een nieuwe positie
     class nieuwePositieListener implements ActionListener
          public void actionPerformed(ActionEvent event)
          {   System.out.println("nieuwe pos");
             Random generator = new Random();
                 for(BewegendeDelen obj : bewegendedelenarray)
                    obj.beweeg();
             repaint();
     //om de vier seconden een nieuwe alien op het scherm
     class nieuweAlienListener implements ActionListener
          public void actionPerformed(ActionEvent event)
          {     //voeg een nieuw alien object aan de array toe en repaint
              System.out.println("nieuwe alien");
               bewegendedelenarray.add(new Alien());
               //repaint();
     //na 15 seconden stopt het spel: Game Over!
     class stopSpelListener implements ActionListener
          public stopSpelListener(int initialCount)
               count = initialCount;
          public void actionPerformed(ActionEvent event)
        {   count--;  
            //als de teller op 0 staat is het spel voorbij
               if (count == 0)
                    nieuwePositieTimer.stop();
                  nieuweAlienTimer.stop();
                  stopSpelTimer.stop();
               else
                System.out.println("time left: " + count);
          //private int count;
     //instantievariabelen
     private int count;
     private int score;
     private boolean gemist;
}     superclass
import java.awt.*;
import java.awt.Graphics2D;
//superclass met gezamenlijke eigenschappen van de bewegende delen ruimteschip, alien en raket
public class BewegendeDelen
     public void paint(Graphics g)
    {      //weergave drawstring met x en y positie
         Graphics2D g2D = (Graphics2D)g;
        g.drawString(weergave, x, y);
     //zet de x positie
     public void setX(int xPos)
          x = xPos;
     //en y positie
     public void setY(int yPos)
          y = yPos;
     public void setWeergave(String deWeergave)
          weergave = deWeergave;
     public String getWeergave()
          return weergave;
     public int getX()
          return x;
     public int getY()
          return y;
     //beweegmethod rechts
     public void beweegRechts()
     {     //verschuif rechts
          x = x + 25;
    //beweegmethod links
     public void beweegLinks()
     {     //verschuif links
          x = x - 25;
     public void beweeg()
     public void verwijder()
     public String toString()
        return weergave + ": (" + x + ", " + y +")";
     //geef de breedte terug
     public int getWidth()
          return width;
     //instantievariabelen
     public int x;
     public int y;
     public String weergave;
     public int width;
} and subclass spaceship
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.Graphics2D;
//subklasse van "bewegendedelen" die eigenschappen ervan erft, en met beweegmethods
public class Ruimteschip extends BewegendeDelen
     public Ruimteschip()
          weergave = "<<=>>";
        x = 250;
         y = 500;
} subclass alien
import java.awt.*;
import java.awt.image.*;
import java.applet.Applet;
//de alien class
public class Alien extends BewegendeDelen
     public Alien()
          weergave = "^^^";
          y = 25;
     public void beweeg()
          x= x+10;
} subclass raket
import java.awt.*;
import java.awt.image.*;
import java.applet.Applet;
public class Raket extends BewegendeDelen
     public Raket(int x, int y)
         weergave = "|";
         setX(x+17);
         setY(y);
     //schietmethod, verticaal omhoog bewegen
     public void beweeg()
          y = y - 40;
     //een lege string als weergave
     public void verwijder()
          weergave = " ";
} So I want to compare whether raket and alien collide...
Thanks!

Similar Messages

  • Compare object from arraylist?

    This is my code
    public int joinedInMonth(int month)
            int members = 0;
            if (month < 1 || month > 12)
                System.out.println(month + "  Is an invalid month");
            }else{
                int index = 0;
                while (index < memberList.size()){
                    if (memberList.get(index) == month) {
                       members+=1;
                index++;
            return members;
        }I get the error operator == cannot be applied to java.lang.object,int
    How can i rectify this?

    Ok I think I am getting there but I have another error.
    public int joinedInMonth(int month)
            int members = 0;
            if (month < 1 || month > 12)
                System.out.println(month + "  Is an invalid month");
            }else{
                int index = 0;
                Membership member;
                while (index < memberList.size()){
                    member = (Membership)memberList.get(index);
                    if (member.getMonth().equals(month)) {
                       members+=1;
                index++;
            return members;
        }

  • Help comparing objects

    Hi,
    My java app's purpose is to find out if I must update my simulated framework if the real framework has changed ( interfaces).
    My app loads two jar files ( real framework and simulated framwork) and use bcel to make an static analysis of the classes ( bcel created 'JavaClass' to describe the class).
    In order to determine if the classes are equal i create a 'DataClass' object with the following information:
    className
    Field [] fields (bcel 'Field' not java.lang.reflect.Field)
    Method [] methods (bcel 'Method' not java.lang.reflect.Method)
    I retrieve the information from JavaClass and put it in my 'DataClass'.
    This is the code I use to create a Vector for each framework ( Listing 1). This is where I store the data describing my classes in the api (Listing 2). Then I compare each 'DataClass' contained in the Vector.
    My intention is to compare the 'data' of the 'DataClass'. But since I get that all DataClass objects are NOT equal I guess I compare references. How can I do this.
    All hints are vey much welcome.
    cheers,
    //mikael
    Listing 1
    ==========
    Note: ClassSet is a 'Set' of JavaClass' objects.
    public static Vector makeDataObjects(ClassSet classes){
            Vector api = new Vector();
            JavaClass [] clazzes = classes.toArray();
            for (int i = 0; i < clazzes.length; i++) {
             JavaClass clazz = clazzes;
    DataClass dc = new DataClass();
    dc.setClassName(clazz.getClassName());
    Field [] fields = clazz.getFields();
    for(int j = 0; j < fields.length; j++){
    dc.setField(fields[j].toString());
    Method [] methods = clazz.getMethods();
    for (int k = 0; k < methods.length; k++) {
    dc.setMethod(methods[k].toString());
    api.add(dc);
    return api;
    Listing 2
    =========
    import java.util.ArrayList;
    public class DataClass implements Comparable{
        private String className = null;
        private ArrayList fields = new ArrayList();
        private ArrayList  methods = new ArrayList();
        public void setClassName(String className){
            this.className = className;
        public String getClassName(){
            return className;
        public void setField(String field){
            fields.add(field);
        public void setMethod(String method){
            methods.add(method);
        public int compareTo(Object o){
    }This is where I compare the content of my two api:s
    Listing 3
    =========
    public static void compare(Vector api1, Vector api2) {
    for (Iterator iter = api1.iterator(); iter.hasNext();) {
       DataClass clazz1 = (DataClass) iter.next();
       String className = (String) clazz1.getClassName();
       DataClass clazz2 = (DataClass) toBeCompared(className, api2);
       // compare object values
       System.out.println("clazz1 is " + clazz1.toString());
       System.out.println("clazz2 is " + clazz2.toString());
       if (clazz1.equals(clazz2)) {
        System.out.println("Objects are the SAME" + className);
       } else {
        System.out.println("Objects are NOT the same" + className);
    private static DataClass toBeCompared(String className, Vector api){
      DataClass dao = null;
      for (Iterator iter = api.iterator(); iter.hasNext();) {
        DataClass element = (DataClass) iter.next();
        String otherClassName = element.getClassName();
        if (className.equals(otherClassName)){
        dao = element;
    return dao;

    Your error is that you implement Comparable and the compareTo method instead of the equals method of Object class. Comparable is needed for ordering items. Equals instead is used to check if two objects are equal. Per convinience it is expected that there is no inconsistency if both equals and compateTo are implemented.
    So you should implement a method in DataClass:
    public boolean equals(Obejct o) {
      boolean result = false;
      if (o instanceof DataClass) {
        DataClass c = (DataClass) o;
        result = className.equals(c.className) &&
             fields.equals(c.fields) &&
             methods.equals(c.methods);
        // keep in mind here, that the arrays fields and
        // methods should be sorted / ordered. use Collections.sort(fields)
        // for this when you create or modify it
      return result;
    }You could also simplify the compare(Vector api1, Vector api2) method when you keep these Vectors sorted for className or use Set (what i dont recommand because of properbly performance drawbacks):
    public static void compare(Vector api1, Vector api2) {
      Collections.sort(api1, new ClassNameComparator());
      Collections.sort(api2, new ClassNameComparator());
      // you should possibly dont do this sorting here because the
      // method name does not state that the vectors are modified
      // but it's a precondition for make the following work properly:
      return api1.equals(api2);
    }i did not compile the code, so i hope i did not make many errors.
    regards
    Sven

  • Checking an object in Arraylist against empty string

    Hi all,
    Im storing a collection of objects in Arraylist.Among them , one of the objects has an empty string.How can i check whether an object contains empty string.I tried to check using the follwing snippet:
    ArrayList idList=new ArrayList();
    if((idList.get(0)) == null || idList.get(0) == "")
            Debug.log("*****ARRAY LIST IS BLANK 1********");Please help

    Here is a bit more deeper code:
    HashMap lookupMap= null;
    try {
              Object obj = util.lookUp(pid,attributeId,params); // The lookUp method returns an object.
                 Debug.log(11, " obj type: " + obj.getClass().getName());
            lookupMap = (HashMap) obj;
    Collection mapkeys = lookupMap.keySet();
    Iterator itKeySet = mapkeys.iterator();
    ArrayList idList = new ArrayList();
    ArrayList descList = new ArrayList();
    ArrayList lookupKeys = new ArrayList();
    while(itKeySet.hasNext())
            lookupKeys.add(itKeySet.next());
    for(int i=0; i<lookupKeys.size(); i++)
            String key = (String)lookupKeys.get(i);
        if(key != null && key.startsWith("1_"))
              idList =(ArrayList)lookupMap.get(lookupKeys.get(i));
            if(key != null && key.startsWith("2_"))
              descList=(ArrayList)lookupMap.get(lookupKeys.get(i));
            if(key != null && key.startsWith("1_") && (size == 1))
               descList=(ArrayList)lookupMap.get(lookupKeys.get(i));
    ArrayList id1=new ArrayList();
    int x=0;
          do
         if(!(idList.get(x)).equals(null) || !(idList.get(x)).equals(""))
                    id1.add(idList.get(x));
                    Debug.log("*****idList.get(x)********"+idList.get(x));
                    Debug.log("*****added to idlist.get(0)********");
                    break;
                  else
                    x++;
         }while(id1.size() == 0);

  • I can't seem to get individual elements when comparing 2 arrays using Compare-Object

    My backup software keeps track of servers with issues using a 30 day rolling log, which it emails to me once a week in CSV format. What I want to do is create a master list of servers, then compare that master list against the new weekly lists to identify
    servers that are not in the master list, and vice versa. That way I know what servers are new problem and which ones are pre-existing and which ones dropped off the master list. At the bottom is the entire code for the project. I know it's a bit much
    but I want to provide all the information, hopefully making it easier for you to help me :)
    Right now the part I am working on is in the Compare-NewAgainstMaster function, beginning on line 93. After putting one more (fake) server in the master file, the output I get looks like this
    Total entries (arrMasterServers): 245
    Total entries (arrNewServers): 244
    Comparing new against master
    There are 1 differences.
    InputObject SideIndicator
    @{Agent= Virtual Server in vCenterServer; Backupse... <=
    What I am trying to get is just the name of the server, which should be $arrDifferent[0] or possibly $arrDifferent.Client. Once I have the name(s) of the servers that are different, then I can do stuff with that. So either I am not accessing the array
    right, building the array right, or using Compare-Object correctly.
    Thank you!
    Sample opening lines from the report
    " CommCells > myComCellServer (Reports) >"
    " myComCellServer -"
    " 30 day SLA"
    CommCell Details
    " Client"," Agent"," Instance"," Backupset"," Subclient"," Reason"," Last Job Id"," Last Job End"," Last Job Status"
    " myServerA"," vCenterServer"," VMware"," defaultBackupSet"," default"," No Job within SLA Period"," 496223"," Nov 17, 2014"," Killed"
    " myServerB"," Oracle Database"," myDataBase"," default"," default"," No Job within SLA Period"," 0"," N/A"," N/A"
    Entire script
    # things to add
    # what date was server entered in list
    # how many days has server been on list
    # add temp.status = pre-existing, new, removed from list
    # copy sla_master before making changes. Copy to archive folder, automate rolling 90 days?
    ## 20150114 Created script ##
    #declare global variables
    $global:arrNewServers = @()
    $global:arrMasterServers = @()
    $global:countNewServers = 1
    function Get-NewServers
    Param($path)
    Write-Host "Since we're skipping the 1st 6 lines, create test to check for opening lines of report from CommVault."
    write-host "If not original report, break out of script"
    Write-Host ""
    #skip 5 to include headers, 6 for no headers
    (Get-Content -path $path | Select-Object -Skip 6) | Set-Content $path
    $sourceNewServers = get-content -path $path
    $global:countNewServers = 1
    foreach ($line in $sourceNewServers)
    #declare array to hold object temporarily
    $temp = @{}
    $tempLine = $line.Split(",")
    #get and assign values
    $temp.Client = $tempLine[0].Substring(2, $tempLine[0].Length-3)
    $temp.Agent = $tempLine[1].Substring(2, $tempLine[1].Length-3)
    $temp.Backupset = $tempLine[3].Substring(2, $tempLine[3].Length-3)
    $temp.Reason = $tempLine[5].Substring(2, $tempLine[5].Length-3)
    #write temp object to array
    $global:arrNewServers += New-Object -TypeName psobject -Property $temp
    #increment counter
    $global:countNewServers ++
    Write-Host ""
    $exportYN = Read-Host "Do you want to export new servers to new master list?"
    $exportYN = $exportYN.ToUpper()
    if ($exportYN -eq "Y")
    $exportPath = Read-Host "Enter full path to export to"
    Write-Host "Exporting to $($exportPath)"
    foreach ($server in $arrNewServers)
    $newtext = $Server.Client + ", " + $Server.Agent + ", " + $Server.Backupset + ", " + $Server.Reason
    Add-Content -Path $exportPath -Value $newtext
    function Get-MasterServers
    Param($path)
    $sourceMaster = get-content -path $path
    $global:countMasterServers = 1
    foreach ($line in $sourceMaster)
    #declare array to hold object temporarily
    $temp = @{}
    $tempLine = $line.Split(",")
    #get and assign values
    $temp.Client = $tempLine[0]
    $temp.Agent = $tempLine[1]
    $temp.Backupset = $tempLine[2]
    $temp.Reason = $tempLine[3]
    #write temp object to array
    $global:arrMasterServers += New-Object -TypeName psobject -Property $temp
    #increment counter
    $global:countMasterServers ++
    function Compare-NewAgainstMaster
    Write-Host "Total entries (arrMasterServers): $($countMasterServers)"
    Write-Host "Total entries (arrNewServers): $($countNewServers)"
    Write-Host "Comparing new against master"
    #Compare-Object $arrMasterServers $arrNewServers
    $arrDifferent = @(Compare-Object $arrMasterServers $arrNewServers)
    Write-Host "There are $($arrDifferent.Count) differences."
    foreach ($item in $arrDifferent)
    $item
    ## BEGIN CODE ##
    cls
    $getMasterServersYN = Read-Host "Do you want to get master servers?"
    $getMasterServersYN = $getMasterServersYN.ToUpper()
    if ($getMasterServersYN -eq "Y")
    $filePathMaster = Read-Host "Enter full path and file name to master server list"
    $temp = Test-Path $filePathMaster
    if ($temp -eq $false)
    Read-Host "File not found ($($filePathMaster)), press any key to exit script"
    exit
    Get-MasterServers -path $filePathMaster
    $getNewServersYN = Read-Host "Do you want to get new servers?"
    $getNewServersYN = $getNewServersYN.ToUpper()
    if ($getNewServersYN -eq "Y")
    $filePathNewServers = Read-Host "Enter full path and file name to new server list"
    $temp = Test-Path $filePathNewServers
    if ($temp -eq $false)
    Read-Host "File not found ($($filePath)), press any key to exit script"
    exit
    Get-NewServers -path $filePathNewServers
    #$global:arrNewServers | format-table client, agent, backupset, reason -AutoSize
    #Write-Host ""
    #Write-Host "Total entries (arrNewServers): $($countNewServers)"
    #Write-Host ""
    #$global:arrMasterServers | format-table client, agent, backupset, reason -AutoSize
    #Write-Host ""
    #Write-Host "Total entries (arrMasterServers): $($countMasterServers)"
    #Write-Host ""
    Compare-NewAgainstMaster

    do not do this:
    $arrDifferent = @(Compare-Object $arrMasterServers $arrNewServers)
    Try this:
    $arrDifferent = Compare-Object $arrMasterServers $arrNewServers -PassThru
    ¯\_(ツ)_/¯
    This is what made the difference. I guess you don't have to declare arrDifferent as an array, it is automatically created as an array when Compare-Object runs and fills it with the results of the compare operation. I'll look at that "pass thru" option
    in a little more detail. Thank you very much!
    Yes - this is the way PowerShell works.  You do not need to write so much code once you understand what PS can and is doing.
    ¯\_(ツ)_/¯

  • COmparing object using console...

    Hi ,
    I want to compare the objects in between the two db schemas. I am using Oracle enterprise console. Here when i am click the compare objects for the tables, i got the below error.
    Cannot perform operation for product"Oracle Change Manager" because another operation is already in progress for the product,or a previous ooperation on the product failed..
    I am getting the above errr. I need to compare the objects now. So how can remove the old operation on the product failes ,
    I am fist time using this console in comparing schems.
    My oracle client is 10.2 cleint ..
    please help me out in comparing the objects ...

    hi:
    Whether did you understand your stub that input by IDL compiler?
    Because the stub extends the org.omg.CORBA.portable.ObjectImpl and provide method _orb() to get current local ORB reference. you do so and repeat your steps in your text.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Convert String Object to Comparable Object

    Getting all types of warnings in Eclipse when I try to cast. I have a method that wants to accept a Comparable<Object> and I would like to pass in a string, float, or integer, and make sure of the Comparable interface.

    EJP wrote:
    Try Comparable<?>. If that doesn't work please post some code.I will continue this thread then.
    inserInSubTree() is to take an attribute and compare it to another using Comparable.
    Here is my code:
    private PrimaryIndexNode insertInSubtree(Comparable<?> newAttribute,
                                            int newByteIndex, PrimaryIndexNode subTreeRoot)
              if (subTreeRoot == null)
                   return new PrimaryIndexNode(newAttribute, newByteIndex, null, null);
              else if(newAttribute.compareTo(subTreeRoot.attribute) < 0)
                   subTreeRoot.leftLink = insertInSubtree(newAttribute,
                                                      newByteIndex, subTreeRoot.leftLink);
                   return subTreeRoot;
              else
                   subTreeRoot.rightLink = insertInSubtree(newAttribute,
                                                      newByteIndex, subTreeRoot.rightLink);
                   return subTreeRoot;
         }I am unfamiliar with generics or the proper use of Comparable. what I desire to do is compare any object for ordering it and subsequently inserting it into a binary tree. I figured Comparable could do this and with auto up and down boxing I can do this for primitives and objects.
    However, unfamiliarity with what I need to do and having no clear example in my resources has left me without remedy.

  • Someone please help creating comparable objects

    I have been given a second part to an assignement that wants me to create a program for comparing student obejects. The assignment description and code are below. I can' t see how the find to method interlocks with the findsmallest because find smallest is already finding the smallest value. I also don't see where the new diffinitions for UMUC_Comparable goes.
    In the second part of this project, you will also find the smallest element in the array, but now the array will be of UMUC_Comparable objects. It will use the compareTo method to compare objects to find the smallest one. This method will also have the name findSmallest, but will take an array of UMUC_Comparable objects. This findSmallest method will have a definition as follows:
    UMUC_Comparable findSmallest(UMUC_Comparable[] array);
    The findSmallest method will use the compareTo method in the UMUC_Comparable interface. You will be using it with the Student objects from module V, section III, so you do not have to rewrite the compareTo method; you can simply use the one defined in the Student object in module V.
    For the second part of this project, you should:
    Create a main that creates an array of Student objects, as in section III of module V. You can use the same array as defined module V. You do not have to read these objects in from a file.
    Call the findSmallest method to find the smallest Student object.
    Use the getName and getAverage methods in the Student object to print out the smallest object.
    Note that the return from the method is a UMUC_Comparable object, not a Student object, so you must cast the returned object to a Student object before printing it out. You can do so as follows:
    Student[] students ....; // Fill in the declaration // of the student array.
    Student s = (Student)findSmallest(UMUC_Comparable[] array);
    /* File: Student.java
    * Author: Darrell Clark
    * Date: December 3, 2006
    * Purpose: Shows how to find the smallest Int value in an array
    import java.util.*;
    import java.io.*;
    public class Student {
    private int average;
    private String name;
    /* public constructor. Note that because no default
    * constructor exists, Student objects will always
    * be constructed with a name and an average.
    public Student(String name, int average) {
    this.average = average;
    this.name = name;
    } // end method
    * return name
    public String getName() {
    return name;
    } // end method
    * return average
    public int getAverage() {
    return average;
    } // end method
    * compare to method for locating smallest value
         public static int findSmallest(int[] array) {
              int min = Integer.MAX_VALUE;
              for (int i = 1; i < (array.length); i++) {
                   if (array[i] < min)
                        min = array;
              return min;
    * compare student value
    public int compareTo(Student student) {
    return (this.average - student.average);
    } // end method
         public static void main(String[] args) {
    Student[] studentArray = { new Student("Tom", 87),
    new Student("Cindy", 100),
    new Student("Pat", 75),
    new Student("Anne", 92),
    new Student("Matt", 82)};
    for (int i = 0; i < studentArray.length; i++) {
    System.out.println(studentArray[i].name + " " +
    studentArray[i].average);
    } // end for
    } // end method
    } // end class

    Were you given the UMUC_Comparable interface, or do you have to write it?
    (1) In the latter case, that is where to start. It includes the method
    compareTo(UMUC_Comparable). This will almost certainly return an
    int - check out the API documentatuon for the Comparable interface.
    (2) What I think the assignment is asking you to do is rewrite the Student
    class so that it implements UMUC_Comparable.
    Then you write the findSmallest(UMUC_Comparable[]) method. There is
    already a static method like this in the (existing) Student class. It's anybody's
    guess where this method is supposed to go - perhaps you could ask
    whoever gave you the assignment. The problem is that it can't go in
    UMUC_Comparable because that's an interface. And it doesn't really belong
    in Student because it is a sort of utility function that deals with any
    UNUC_Comparable array.
    (3) Let's assume that findSmallest(UMUC_Comparable[]) goes in the
    Student class. So you replace the existing findSmallest() with the new one.
    The new one goes through the array using the UMUC_Comparable's
    compareTo() method to find the smallest UMUC_Comparable.
    (4) Finally in main() you create a test array, use the newly rewritten
    findSmallest() to find the smallest Student, and print their name and
    average.

  • Comparing objects from system other  system

    Hi,
    I need to compare the multiprovider from development system to production system.Is there is any program  avilable to compare objects. Please share.
    Thanks,
    vikk

    Hi Vikk,
    The important thing for multiprovider is characteristics and key figures identification.
    Use table RSDICMULTIIOBJ for getting the complete list of infoobjects having identification in multiprovider. Now you can either download the complete mapping in two excel sheet and then do the comparison using some vlookup technique.
    Or You can simply do the online comparison over development and production system.
    Regards,
    Durgesh.

  • Comparing objects for equality with UDT's

    Hi.
    I was wondering how Oracle does comparison for equality of objects that contains parameters of user defined types.
    Suppose I have an object with a parameters whose types are:
    1) number,
    2) varchar2,
    3) nested table type,
    4) associative array
    and I want to compare two such objects for equality. Would Oracle compare all parameters of this 2 compared objects field-by-field (and dig recursive to "leafs"), or would it compare only 1), 2) and doas nothing with 3) and 4)?
    Must I declare an order method for such comparison?

    You didn't specify a version - this is correct for 10.2, I'm not sure if it has changed in 11g.
    By default it will compare for exact equality - i.e that every attribute is the same. You can also only do it in SQL, not PL/SQL. Also can only do = and <> - you cannot do < or > etc.
    You need to create a MAP or ORDER method on the type to do any more sophisticated comparison (Same as in most object oriented languages). Documentation is here http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14260/adobjbas.htm#sthref211

  • Help with adding a progress bar to my compare-object script

    I have a simple compare object script that I would like to add some kind of intelligent progress bar or countdown timer to.  The script takes anywhere from 1-12 hours to run depending on the folder sizes.  Here is the script:
    $internal = Get-ChildItem -Recurse -path C:\Folder1
    $external = Get-ChildItem -Recurse -path C:\Folder2
    Compare-Object -ReferenceObject $internal -DifferenceObject $external | Out-File C:\compare_list.txt
    I have a progress bar script that I found but I do not know how to implement it into my existing script.  Here it is:
    for ($i = 1; $i -le 100; $i++) {Write-Progress -Activity 'counting' -Status "
    $i percent" -PercentComplete $i ; sleep -Milliseconds 20}
    Any help is much appreciated.

    Hi Brisketx,
    In addition, to add a Progress Bar to Your PowerShell Script, this article may be helpful for you:
    Add a Progress Bar to Your PowerShell Script:
    http://blogs.technet.com/b/heyscriptingguy/archive/2011/01/29/add-a-progress-bar-to-your-powershell-script.aspx
    I hope this helps.
    We
    are trying to better understand customer views on social support experience, so your participation in this
    interview project would be greatly appreciated if you have time.
    Thanks for helping make community forums a great place.

  • Directly access specified item in Compare-object results

    I have done a Compare-Object and assigned the results to the array variable $NeedToConform. I can iterate through the variable with foreach ($Item in $NeedToConform) and get $Item.SideIndicator, but in my case I already have the item in question in $Package,
    and I need to get at the SideIndicator of that specific item. Basically $NeedToConform.$Package.SideIndicator, but that doesn't work. I tried using a dictionary instead of an array, with no joy. 
    Is there a trick here, or should I just punt and step through the array each time?
    EDIT: Damn, why do I so often find a solution right after posting the question. And why don't I learn and post the question sooner, so I'll find the solution sooner? ;) Anyway, this works.
    if ($NeedToConform[[array]::indexof($NeedToConform,$Package)].SideIndicator -eq '<=')
    I just wonder, is indexof really just a convenience method that iterates for me? If I might have a hundred or more results in the $NeedToConform array, and I might need to test against a hundred values for $Package, do I have any performance implications
    to worry about?
    Gordon

    mjolinor,
    my failure with Dictionary was on multiple fronts.
    One, you need to compare two dictionaries. But one of my objects needs to be ordered, and it needs to work in v2, so an ordered dictionary isn't an option. I may have been able to get it to work, but indexof works with the array, so that is my solution for
    now. But I am flagging this to come back to for review down the road. Always something new to learn.
    Thanks!
    Gordon
    You can have an ordered dictionary in V2:
    $OrderedHT = New-Object collections.specialized.ordereddictionary
    You just didn't see it used very often because you couldn't use it to create an object very easily.  The -properties parameter of New-Object would only take a generic/unordered dictionary as an argument.
    They fixed that in V3, along with adding the type accelerator ([ordered]) to make it easier to create an ordered dictionary.
    [string](0..33|%{[char][int](46+("686552495351636652556262185355647068516270555358646562655775 0645570").substring(($_*2),2))})-replace " "

  • I need help with comparing Objects of an ArrayList

    Hi,
    I am trying to compare a certain variable of objects which are stored in an arrayList.
    for example i have a class called AuctionBid(String bidderID, BitSet itemSet, int bidValue)
    and i have another class called AuctionBidFactory which creates AuctionBid objects and stores them into an arrayList
    I have another Gui class which acts as a user interface where the user can create bids but then i want to compare the itemSet of the AuctionBid which is created by the user to the itemSets of the AuctionBid objects which already exist in the arrayList and if that itemSet does not exist in the arraylist then will add the new AuctionBid to the arrayList.
    I have the following method in the AuctionBidFactory which is supposed to compare the itemSets of the AuctionBids in the arrayList and it does not work:
    public boolean containsItem(AuctionBid auctionBid) {
              if (auctionBids.contains(auctionBid.itemSet)) {
                   return true;
              return false;
    where auctionBids is the arrayList where the AuctionBid objects are stored
    I hope the information above is enough to see where the problem is.
    many thanks

    Amit, unfortunately I dont have a different object for the user bids. Basically I just have the AuctionBid(String bidder,BitSet items, int value) and the reason why im using bitSet is that im modelling a combinatorial auction where the bidder can bid on combination of items.
    now when the user puts a bid that bid is added to an arrayList of ArrayList<AuctionBid>
    then once all the bidings have finished i want to create autoBids for those single items only for which there are no bids. so for example lets say there are 6 items for auction and if there are the following bids in the arrayList:
    AuctionBid(bidder1,{1},5)
    AuctionBid(bidder2,{5},8)
    i want to create autobids as follow:
    AuctionBid(autoBid,{0},0)
    AuctionBid(autoBid,{2},0)
    AuctionBid(autoBid,{3},0)
    AuctionBid(autoBid,{4},0)
    and then i want to add these created bids to the same arrayList where all the bids are.
    but if I use the arrayList.contains() method it will compare the whole objects to each other rather than just comparing the bitSets(items) in each bid.
    so i dont know whether i can still do this without overriding the equals() method in the AuctionBid class or not
    regards
    Arneh

  • Confused about objects in ArrayLists

    Alright, this is what I am trying to do:
    1.I collect the first name, last name, number, points, rebounds, assists, and fouls all in the stats object.
    Here is my main code:
        public static void main(String[] args) {
            String input;
            String input1;
            String firstName;
            String lastName;
            int gameNumber = 0;
            int points = 0;
            int rebounds = 0;
            int fouls = 0;
            int assists = 0;
            int i = 0;
            ArrayList<Stats> player = new ArrayList<Stats>();
            do{
                Stats stats = new Stats();
                Scanner keyboard = new Scanner(System.in);
                System.out.println("Do you want to enter data or quit(E-enter, Q-quit)?");
                input1 = keyboard.nextLine();
                if (input1.equalsIgnoreCase("E")){
                    System.out.println("What is player's first name? ");
                    firstName = keyboard.nextLine();
                    stats.setFirstName(firstName);
                    System.out.println("What is player's last name? ");
                    lastName = keyboard.nextLine();
                    stats.setLastName(lastName);
                    System.out.println("What is player's game number? ");
                    gameNumber = keyboard.nextInt();
                    stats.setGameNumber(gameNumber);
                    System.out.println("How many points were scored? ");
                    points = keyboard.nextInt();
                    stats.setPoints(points);
                    System.out.println("How many rebounds? ");
                    rebounds = keyboard.nextInt();
                    stats.setRebounds(rebounds);
                    System.out.println("How many fouls? ");
                    fouls = keyboard.nextInt();
                    stats.setFouls(fouls);
                    System.out.println("How many assists? ");
                    assists = keyboard.nextInt();
                    stats.setAssists(assists);
                    player.add(stats);
                System.out.println(stats);
                System.out.println("Do you want to get a players info or average, enter or quit (I-Info, A-average,E-entry,Q-quit)?");
                input = keyboard.nextLine();
                System.out.println(input);
            } while (!input.equalsIgnoreCase("Q"));
    }I also have a Stats.java code that gets/sets each points rebounds...etc.
    And thats all fine.... but now I want to put stats in an ArrayList, and be able to access each added stats by the user typing a last name.
    AKA:
    Input: Thompson
    Output: points, rebounds, assists, fouls
    So am I on the right road by just adding stats into player every loop, and how do I access it with just a last name?
    If u do not understand just ask and Ill explain better.
    Thanks guys

    Ight thanks, I got that to work but now I have another question....
    Here is my code:
      public static void main(String[] args) {
            String input;
            String input1;
            String firstName;
            String lastName;
            int gameNumber = 0;
            int points = 0;
            int rebounds = 0;
            int fouls = 0;
            int assists = 0;
            ArrayList s1 = new ArrayList<Stats>();
            do{
                Stats stats = new Stats();
                Scanner keyboard = new Scanner(System.in);
                System.out.println("Do you want to enter data or quit(E-enter, Q-quit)?");
                input1 = keyboard.nextLine();
                if (input1.equalsIgnoreCase("E")){
                System.out.println("What is player's first name? ");
                firstName = keyboard.nextLine();
                stats.setFirstName(firstName);
                s1.add(firstName);
                System.out.println("What is player's last name? ");
                lastName = keyboard.nextLine();
                stats.setLastName(lastName);
                s1.add(lastName);
                System.out.println("What is player's game number? ");
                gameNumber = keyboard.nextInt();
                stats.setGameNumber(gameNumber);
                s1.add(gameNumber);
                System.out.println("How many points were scored? ");
                points = keyboard.nextInt();
                stats.setPoints(points);
                s1.add(points);
                System.out.println("How many rebounds? ");
                rebounds = keyboard.nextInt();
                stats.setRebounds(rebounds);
                s1.add(rebounds);
                System.out.println("How many fouls? ");
                fouls = keyboard.nextInt();
                stats.setFouls(fouls);
                s1.add(fouls);
                System.out.println("How many assists? ");
                assists = keyboard.nextInt();
                stats.setAssists(assists);
                s1.add(assists);
                System.out.println("Do you want to get a players info or average, enter or quit (I-Info, A-average,E-entry,Q-quit)?");
                input = keyboard.nextLine();
                System.out.println(input);
                /*if (input.equalsIgnoreCase("I")){
                    System.out.println("Enter player's last name: ");
                    String lastNameInfo = keyboard.nextLine();
                    for (int i=1; i<s1.size(); i=i+7){
                        if (lastNameInfo.equalsIgnoreCase((String)s1.get(i))) {
                            System.out.println((String)s1.get(i-1) + (String)s1.get(i) + " had " +
                                    (String)s1.get(i+2) + " points, " + (String)s1.get(i+3) +
                                    " rebound, " + (String)s1.get(i+4) + "fouls, and " +
                                    (String)s1.get(i+5) + "assists.");
                        } else;
                        System.out.println("That player is not on the roster.");
            } while (input.equalsIgnoreCase("E"));
    }And here is my output:
    init:
    deps-jar:
    compile:
    run:
    Do you want to enter data or quit(E-enter, Q-quit)?
    e
    What is player's first name?
    Jon
    What is player's last name?
    Doe
    What is player's game number?
    1
    How many points were scored?
    1
    How many rebounds?
    1
    How many fouls?
    1
    How many assists?
    1
    Do you want to get a players info or average, enter or quit (I-Info, A-average,E-entry,Q-quit)?
    BUILD SUCCESSFUL (total time: 13 seconds)Why does it not let the user put an answer in for the last question ("Do you want to get a players info or average, enter or quit (I-Info, A-average,E-entry,Q-quit)?")
    Thanks

  • Remove Object from ArrayList

    Hi,
    i want to remove an object from my ArrayList. The Array-List contains objects from a class like this:
    public class Data {
         String id;
         String name;
         String data;
         //getters
         //setters
    myArrayList.remove(myData);
    This doesn't work! Why not? What is wrong?
    Daniel

    The ArrayList determines which element to delete by the equals() method. The default implementation of equals() tests for instance identity. So two instances of your class with absolutely identical data fields will not match! You probably just need to override the default equals() with a proper implementation and everything will work.

Maybe you are looking for