Sort array list and using comparable

With the following code I would like to setup a score object for the current player.
Change it to a string(Is it correct to say parse it to a string type)
Then add it to the arraylist.
So I can sort the array list according to the string size.
That's why I have the variables in that order.
So if 3 players have the same amount of guesses, they can be positioned on the high score list according to their gameTime.
//create score object
               Score currentScore = new Score(guessCount, gameTime, name);
               String currentScoreToString = currentScore.toString();
               //add score to arrayList
               scores.add(currentScoreToString);So the error message says " The method add(Score) in the type arrayList <Score> is not applicable for the arguments(string)"
Now, I understand that, I would like to know if there is another way to achieve what I am trying to do.
Is the string idea I am trying here possible? is it practical or should I use comparable?
I have looked at comparable, but I don't get it.
Will my Score class implement comparable. I am looking at an example with the following code.
Employee.java
public class Employee implements Comparable {
    int EmpID;
    String Ename;
    double Sal;
    static int i;
    public Employee() {
        EmpID = i++;
        Ename = "dont know";
        Sal = 0.0;
    public Employee(String ename, double sal) {
        EmpID = i++;
        Ename = ename;
        Sal = sal;
    public String toString() {
        return "EmpID " + EmpID + "\n" + "Ename " + Ename + "\n" + "Sal" + Sal;
    public int compareTo(Object o1) {
        if (this.Sal == ((Employee) o1).Sal)
            return 0;
        else if ((this.Sal) > ((Employee) o1).Sal)
            return 1;
        else
            return -1;
ComparableDemo.java
import java.util.*;
public class ComparableDemo{
    public static void main(String[] args) {
        List ts1 = new ArrayList();
        ts1.add(new Employee ("Tom",40000.00));
        ts1.add(new Employee ("Harry",20000.00));
        ts1.add(new Employee ("Maggie",50000.00));
        ts1.add(new Employee ("Chris",70000.00));
        Collections.sort(ts1);
        Iterator itr = ts1.iterator();
        while(itr.hasNext()){
            Object element = itr.next();
            System.out.println(element + "\n");
}The thing I don't understand is why it returns 0, 1 or -1(does it have to do with the positioning according to the object is being compared with?)
What if I only use currentScore in a loop which loops every time the player restarts?
//create score object
               Score currentScore = new Score(guessCount, gameTime, name);
               String currentScoreToString = currentScore.toString();
               //add score to arrayList
               scores.add(currentScoreToString);Also why there is a method compareTo, and where is it used?
Thanks in advance.
Edited by: Implode on Oct 7, 2009 9:27 AM
Edited by: Implode on Oct 7, 2009 9:28 AM

jverd wrote:
Implode wrote:
I have to hand in an assignment by Friday, and all I have to do still is write a method to sort the array list. Okay, if you have to write your own sort method, then the links I provided may not be that useful. They show you how to use the sort methods provided by the core API. You COULD still implement Comparable or Comparator. It would just be your sort routine calling it rather than the built-in ones.
You have two main tasks: 1) Write a method that determines which of a pair of items is "less than" the other, and 2) Figure out a procedure for sorting a list of items.
The basic idea is this: When you sort, you compare pairs of items, and swap them if they're out of order. The two main parts of sorting are: 1) The rules for determining which item is "less than" another and 2) Determining which pairs of items to compare. When you implement Comparable or create a Comparator, you're doing #1--defining the rules for what makes one object of your class "less than" another. Collections.sort() and other methods in the core API will call your compare() or compareTo() method on pairs of objects to produce a sorted list.
For instance, if you have a PersonName class that consists of firstName and lastName, then your rules might be, "Compare last names. If they're different, then whichever lastName is less indicates which PersonName object is less. If they're the same, then compare firstNames." This is exactly what we do in many real-life situations. And of course the "compare lastName" and "compare firstName" steps have their own rules, which are implemented by String's compareTo method, and which basically say, "compare char by char until there's a difference or one string runs out of chars."
Completely independent of the rules for comparing two items is the algorithm for which items get compared and possibly swapped. So, if you have 10 Whatsits (W1 through W10) in a row, and you're asked to sort them, you might do something like this:
Compare the current W1 to each of W2 through W10 (call the current one being compared Wn). If any of them are less than W1, swap that Wn with W1 and continue on, comparing the new W1 to W(n+1) (that is, swap them, and then compare the new first item to the next one after where you just swapped.)
Once we reach the end of the list, the item in position 1 is the "smallest".
Now repeat the process, comparing W2 to W3 through W10, then W3 to W4 through W10, etc. After N steps, the first N positions have the correct Whatsit.
Do you see how the comparison rules are totally independent of the algorithm we use to determine which items to compare? You can define one set of comparison rules ("which item is less?") for Whatsits, another for Strings, another for Integers, and use the same sorting algorithm on any of those types of items, as long as you use the appropriate comparison rules.Thanks ;)
massive help
I understand that now, but I am clueless on how to implement it.
Edited by: Implode on Oct 7, 2009 10:56 AM

Similar Messages

  • Sorting array list

    can u please give me the source code for:
    sorting array list for ascending and descending order

    You already have the source code.

  • Sort Array List

    Hi,
    I have an array List which have values like empid, amount, corpcode eg.
    223, 345.95, SDB
    791, 567.75, XYZ
    115, 345.95, SDB
    I need to sort this array like this
    115, 345.95, SDB
    223, 345.95, SDB
    791, 567.75, XYZ
    How can I do this?
    Thanks

    You have to implement a natural order for your object, so that it can be sorted. There are a lot of tutorials out there for this, but I will do it anyway for you:
    public YourClass implements Comparable<YourClass>{
    int firstNumber;
    int secondNumber;
    int thirdNumber;
    String someIdentifier;
    public int compareTo(YourClass otherObject){
       int difference = this.firstNumber - otherObject.firstNumber;
       if(difference != 0) return difference;
       difference = this.secondNumber - otherObject.secondNumber;
       if(difference != 0) return difference;
       return this.someIdentifier.compareTo(otherObject.someIdentifier);
    }As you can see, the basic idea is, that you return if an object is greater, equal or less than another. You begin with the most important criteria. If this one is equal, you check the next one.
    Some objects already include the comparable interface, like String. If this is the case, you can take advantage of this, and use their compareTo Method.
    After this, you can sort your objects with
    Collections.sort(someList);

  • Sort array(list) of files on filename

    Hey all,
    Is there a way to sort an array(list) of files on the names of those files. (the files are not in same directory)
    Thanks

    Gogoe wrote:
    Hey all,
    Is there a way to sort an array(list) of files on the names of those files. (the files are not in same directory)
    Thanks
    Why do you need to sort the actual Files? Can't you just sort the list of name using Arrays.sort()? Once the names are in order you call up the Files in the order you read the names. Or is there more to the request yet?

  • Iterating thru an array list and displaying it on the table.

    Hi All,
    I have done table binding.
    Say if I have a list of values(pojo's) in the request scope. I need to iterate thru the list and display the attributes enclosed inside the pojo on a JSF page.
    How do I achieve it?
    Thanks
    - Gana.

    Hi,
    it depends on what you mean by "I have done the table binding". A Pojo can be used as the base for a data control, which then can be bound to a table through this (using ADF).
    If you want to copy values to a table, you can access the binding container in a managed bean (you didn't tell the technology you use so i assume JSF). Check SRDemo on how to access the binding container in a managed bean (see SRMain for example)
    Frank

  • I am using array list and retuning as list i am getting class cast exceptio

    Hi
    below is my code
    public List fun(){
    List list=new ArrayList()
    return(list)
    public main()
    List samp=xxx.fun();
    its throwing a class cast exception
    please help me
    thnaks
    sreedevi

    QCDataInfo condInfo;
    if(conditions!=null){
         ListIterator li = conditions.listIterator();
    while (li.hasNext()) {
    condInfo = (QCDataInfo) li.next();
    stmt = conn.getConnection().prepareStatement(sql);
         stmt.setLong(1, JLong.forceLong(loanId));
         stmt.setString(2,condInfo.getCategory());
         stmt.setString(3,condInfo.getCleared());
         stmt.setString(4, condInfo.getMessage());
         stmt.setString(5, condInfo.getNotes());
         System.out.println(condInfo.getCategory()+"=dtstus="+condInfo.getCleared()+"=execute:="+stmt.executeUpdate());
    public static List getQCDataInfo(String loanId)
    throws ACTPortalException {
    info = new ArrayList();
    int x=0,a=0,b=0,c=0,d=0,e=0,f=0;
    while(rs.next()) {
         QCDataInfo xform=new QCDataInfo();
         xform.setCategory(rs.getString("category"));
    xform.setCleared(rs.getString("cleared"));
    xform.setMessage(rs.getString("message"));
    xform.setUpdated(rs.getString("updated"));
    xform.setNotes(rs.getString("notes"));
    if(rs.getString("category").equals("Occupancy")){
    xform.setIndex(x);x++;
              }else if(rs.getString("category").equals("Liabilities")){
                   xform.setIndex(a);a++;
              }else if(rs.getString("category").equals("Assets")){
                   xform.setIndex(b);b++;                    
              }else if(rs.getString("category").equals("REO")){
                   xform.setIndex(c);c++;
              }else if(rs.getString("category").equals("Collateral")){
                   xform.setIndex(d);d++;
              }else if(rs.getString("category").equals("Employment and Income")){
                   xform.setIndex(e);e++;
              } else if(rs.getString("category").equals("Other")){
                   xform.setIndex(f);f++;
    // System.out.println("data:"+rs.getString("category")+":row number:"+rs.getRow());
    info.add(xform);
    return (info);
    the above are 2 methods where i am getting class cast exception
    =21 Apr 2006 10:16:44,828 JLogger->Caught exception in AuthorizationFilter.doFilter: null
    java.lang.ClassCastException
         at org.apache.struts.util.RequestUtils.lookupActionForm(RequestUtils.java:215)
         at org.apache.struts.util.RequestUtils.createActionForm(RequestUtils.java:181)
         at org.apache.struts.action.RequestProcessor.processActionForm(RequestProcessor.java:321)
         at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:204)
         at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1164)
         at org.apache.struts.action.ActionServlet.doGet(ActionServlet.java:397)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:689)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
         at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:237)
         at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:157)
         at com.mindbox.app.CompressionFilter.doFilter(CompressionFilter.java:199)
         at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:186)
         at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:157)
         at com.mindbox.app.DemoAccountFilter.doFilter(DemoAccountFilter.java:49)
         at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:186)
         at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:157)
         at com.mindbox.app.AuthorizationFilter.doFilter(AuthorizationFilter.java:66)
         at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:186)
         at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:157)
         at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:214)
         at org.apache.catalina.core.StandardValveContext.invokeNext(StandardValveContext.java:104)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:520)
         at org.apache.catalina.core.StandardContextValve.invokeInternal(StandardContextValve.java:198)
         at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:152)
         at org.apache.catalina.core.StandardValveContext.invokeNext(StandardValveContext.java:104)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:520)
         at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:137)
         at org.apache.catalina.core.StandardValveContext.invokeNext(StandardValveContext.java:104)
         at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:118)
         at org.apache.catalina.core.StandardValveContext.invokeNext(StandardValveContext.java:102)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:520)
         at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
         at org.apache.catalina.core.StandardValveContext.invokeNext(StandardValveContext.java:104)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:520)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:929)
         at org.apache.coyote.tomcat5.CoyoteAdapter.service(CoyoteAdapter.java:160)
         at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:799)
         at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.processConnection(Http11Protocol.java:705)
         at org.apache.tomcat.util.net.TcpWorkerThread.runIt(PoolTcpEndpoint.java:577)
         at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:683)
         at java.lang.Thread.run(Thread.java:534)
    the above is the eeror which i am geeting when i call those methods
    i thought there is a something wrong
    thanks
    sreedevi

  • I upgraded to PSE 13 so I could edit RAW files from my Sony a6000 but PSE 13 is not recognizing any of the RAW files. My Sony a6000 is on the Camera Raw list and uses version 8.4. PSE 13 uses Version 8.6. Why isn't it recognizing the files?.

    Why isn't PSE13 recognizing my Sony a6000 RAW files?

    Not sure if upgrading to 8.7 would make any difference.  Photoshop has 8.7 so worth a try:
    I don't use PSE13 yet so don't know if this upgrade is available for it.

  • 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.
    ¯\_(ツ)_/¯

  • Sort column by without case sensitive  using Comparator interface

    Hello,
    When i sorted my values of a column in a table it was showing all sorted upper case letters at top rows and all sorted lower case letters on bottom. So i would like to sort values without case sensitive order. Like. A, a, B, b, C, c....
    I am using Collection class to sort vector that contains the values of a column as an object and using Comparator interface to sort the values of a column in either ascending and descending order. It facilitates to compare two objects like.
    <class> Collections.sort(<Vector contains values of column to be sort>, <Comparator interface>);
    and in interface it compares two objects ((Comparable) object).compareTo(object);
    Now Let's suppose i have three values say Z, A, a to sort then this interface sorted in ascending order like A, Z, a
    but the accepted was A, a, Z. So how can i get this sequence. I would like to sort the values of a column without case sensitive manner.
    Thanks
    Ashish Pancholi
    Edited by: A.Pancholi on Dec 29, 2008 1:36 PM

    [http://java.sun.com/javase/6/docs/api/java/lang/String.html#CASE_INSENSITIVE_ORDER]

  • Need script to read a list and compare it to the contents of a folder...

    I need a script that will read all of the file names within a tab delimited list and then compare them to the files within a directory (named IMAGES) and delete the files of this IMAGES folder that are not included in the list.
    Thanks in advance.

    It won't work because of what you're comparing.
    Consider if files_list does not contain (image_file as string) then.
    Your script defines files_list as the contents of the specified file like:
    "file1.jpg
    file2.jpg
    file3.png"
    and image_file is a list of files which, when coerced to a string looks like:
    "Cabezon:Users:cochino:Desktop:images:file1.jpgCabezon:Users:cochino:Desktop:ima ges:file2.jpgCabezon:Users:cochino:Desktop:images:file3.png".
    There is no way files_list is going to be in image_file.
    Instead you're going to have to iterate through one or other of the lists and find matches.
    Since the list of files you want to keep is around 1,000 items long, and there are 6,000 files in the directory it would be quicker to iterate through the list of files to keep (a loop of 1000 iterations) than it would be to loop through the files to see which ones to delete (a loop of 6000 iterations).
    Therefore your best bet is something like this (untested):
    tell application "Finder"
    --define the source directory
    set sourceDir to folder "Cabezon:Users:cochino:Desktop:images:"
    -- create a temp dir for the files to keep
    set filesToKeepFolder to (make new folder at (path to temporary items) with properties {name:"TempImageDir"})
    -- get the list of files to keep
    set files_list to paragraphs of (read file "Cabezon:Users:cochino:Desktop:Workbook2.txt")
    -- iterate through them
    repeat with eachFile in files_list
    try
    -- move the file to the temp folder
    move file (eachFile as text) of sourceDir to filesToKeepFolder
    end try
    end repeat
    -- by the time you get here all the matched files
    -- have been moved to the temp dir
    -- so now you can throw away the rest of the files
    delete every file of sourceDir
    -- and copy the files you want back in
    move every file of filesToKeepDir to sourceDir
    -- and clean up
    delete filesToKeepDir
    end tell
    The comments should give you some idea as to what it's doing, but in short it walks through the list of files looking for matching files in the specified directory. If it finds a match it moves that file to a temporary directory. At the end of the 1,000 iterations, what's left in the directory are the files that did not match the file read in at the beginning, so these files can be deleted.
    Finally, to clean up, the files you want are copied back into the images directory and the temporary directory is deleted.

  • How to find and display the posistion in an array list

    hi all,
    i know this is proballly simple but i have an arraylist where every time someone connects to my system it adds them to an arraylist, how can i post back somelike like hi user "1" thanks for connecting and so on. i just dont understand how to find their unique posistion in the array list and display it as a number.
    any help would be great

    So to be clear...
    You have an arraylist of connections .... for example
    ArrayList<ConnectedPeople> connPplArr = new ArrayList();And then each time someone connects you would add a connected people object to the arraylist.
    ConnectedPeople, migh contain username etc etc.
    You could then do:
    ConnectedPeople newConnection..... ;
    int index = connPplArr.indexOf( newConnection );
    if(int == -1){
        add them to your array
        index = connPplArr.size();
    return "Hello user "+ index;That what you mean?
    I know some of it is sudo code, but have I understood your problem?
    Edited by: Azzer_Mac on Apr 29, 2008 2:20 AM
    Edited by: Azzer_Mac on Apr 29, 2008 2:20 AM

  • Problem passing multiple array lists to a single method

    Hi, all:
    I have written a generic averaging method that takes an array list full of doubles, adds them all up, divides by the size of the array list, and spits out a double variable. I want to pass it several array lists from another method, and I can't quite figure out how to do it. Here's the averager method:
         public double averagerMethod (ArrayList <Double> arrayList) {
              ArrayList <Double> x = new ArrayList <Double> (arrayList); //the array list of integers being fed into this method.
              double total = 0;//the total of the integers in that array list.
              for (int i = 0; i < x.size(); i++) {//for every element in the array list,
                   double addition = x.get(i);//get each element,
                   total = total + addition; //add it to the total,
              double arrayListSize = x.size();//get the total number of elements in that array list,
              double average = total/arrayListSize;//divide the sum of the elements by the number of elements,
              return average;//return the average.
         }And here's the method that sends several array lists to that method:
         public boolean sameParameterSweep (ArrayList <Double> arrayList) {
              sameParameterSweep = false;//automatically sets the boolean to false.
              arrayList = new ArrayList <Double> (checker);//instantiate an array list that's the same as checker.
              double same = arrayList.get(2); //gets the third value from the array list and casts it to double.
              if (same == before) {//if the third value is the same as the previous row's third value,
                   processARowIntoArrayLists(checker);//send this row to the parseAParameterSweep method.
                   sameParameterSweep = true;//set the parameter sweep to true.
              if (same != before) {//if the third value is NOT the same,
                   averagerMethod(totalTicks);//go average the values in the array lists that have been stored.
                   averagerMethod(totalNumGreens);
                   averagerMethod(totalNumMagentas);
                   sameParameterSweep = false;
              before = same; //problematic!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
         return sameParameterSweep;
         }Obviously, the problem is that I'm not passing the array lists from this method to the averager method the right way. What am I doing wrong?

    Encephalopathic wrote:
    There are several issues that I see, but the main one is that you are calculating average results but then just discarding them. You never assign the result to a variable.
    In other words you're doing this:
    averagerMethod(myArrayList);  // this discards the resultinstead of this:
    someDoubleVariable = averagerMethod(myArrayList); // this stores the resultAlso, do you wish to check for zero-sized array lists before calculating? And what would you return if the array list size were zero?So in solving that problem, I've come up with another one that I can't figure out, and I can't fix this problem until I fix that.
    I have several thousand lines of data. They consist of parameter sweeps of given variables. What I'm trying to do is to store pieces of
    data in array lists until the next parameter adjustment happens. When that parameter adjustment happens, I want to take the arraylists
    I've been storing data in, do my averaging thing, and clear the arraylists for the next set of runs under a given parameter set.
    Here's the issue: I'm having the devil of a time telling my application that a given parameter run is over. Imagine me doing stuff to several variables (number of solders, number of greens, number of magentas) and getting columns of output. My data will hold constant the number of soldiers, and for, say, ten runs at 100 soldiers, I'll get varying numbers of greens and magentas at the end of each of those ten runs. When I switch to 150 soldiers to generate data for ten more runs, and so forth, I need to average the number of greens and magentas at the end of the previous set of ten runs. My problem is that I can't figure out how to tell my app that a given parameter run is over.
    I have it set up so that I take my data file of, say, ten thousand lines, and read each line into a scanner to do stuff with. I need to check a given line's third value, and compare it to the previous line's third value (that's the number of soldiers). If this line has a third value that is the same as the previous line's third value, send this line to the other methods that break it up and store it. If this line has a third value that is NOT the same as the previous line's third value, go calculate the averages, clear those array lists, and begin a new chunk of data by sending this line to the other methods that break it up and store it.
    This is not as trivial a problem as it would seem at first: I can't figure out how to check the previous line's third value. I've written a lot of torturous code, but I just deleted it because I kept getting myself in deeper and deeper with added methods. How can I check the previous value of an array list that's NOT the one I'm fiddling with right now? Here's the method I use to create the array lists of lines of doubles:
         public void parseMyFileLineByLine() {
              totalNumGreens = new ArrayList <Double>();//the total number of greens for a given parameter sweep
              totalNumMagentas = new ArrayList <Double>();//the total number of magentas for a given parameter sweep.
              totalTicks = new ArrayList <Double>();//the total number of ticks it took to settle for a given parameter sweep.
              for (int i = 8; i < rowStorer.size() - 2; i++) {//for each line,
                   checker = new ArrayList <Double>();//instantiates an array list to store each piece in that row.
                   String nextLine = rowStorer.get(i); //instantiate a string that contains all the information in that line.
                   try {
                        Scanner rowScanner = new Scanner (nextLine); //instantiates a scanner for the row under analysis.
                        rowScanner.useDelimiter(",\\s*");//that scanner can use whitespace or commas as the delimiter between information.
                        while (rowScanner.hasNext()) {//while there's still information in that scanner,
                             String piece = rowScanner.next(); //gets each piece of information from the row scanner.
                             double x = Double.valueOf(piece);//casts that stringed piece to a double.
                             checker.add(x);//adds those doubles to the array list checker.
                   catch (NoSuchElementException nsee) {
                        nsee.printStackTrace();
                   //System.out.println("checker contains: " + checker);
                   processARowIntoArrayLists(checker);//sends checker to the method that splits it up into its columns.
         }

  • Which is lightweight array list or string tokenizer

    which is lightweight array list or string tokenizer:
    I am reading a flat file and doing some text parsing to find some records which matched my search criteria.
    The flat file will have 5K records at the average and each records is in each line. (\n) is the delimiter to the string tokenizer.
    My Doubt is:
    Will it be good to manipulate all the records to the array list and then manipulating and achieve my task or
    Will it be good if i do a just string tokenizer and achieve my task with out an arraylist.
    Note: There is no unique fields in the records so no way to use hashmap/table.

    DrClap wrote:
    Faster? Actually the stated requirements were "lightweight" and "good". It guess I assumed what they usually mean to me.
    However answering this a different way.
    lightweight - your computer won't be heavier no matter which way you choose.
    good - it will have no barring on your concious or your place in the after life.
    good(2) - Write it the simplest way you think you can and worry about performance later if its a problem.

  • How to query the sharepoint list with using lookup column

    hi,
    I have requrement like below
     List A
    Title                         Postionid(Lookup)       PositionDescription
    [email protected]             1                              
    xxxx
    [email protected]             1                               
    xxx
    [email protected]           1                                
    xxx
    [email protected]                    2                               
    sss
    [email protected]             2                               
    www
    List B
    Title                         fistname  lastname age fathername
    [email protected]         x             x             10      y
    [email protected]         p            p               12      p
    [email protected]               q           q                12    
    y
     here in List A positionid is lookup column i have creating one visual web part i am querying the List A using  query string as Positionid in that web part .finally what i want is i need date from list B on basis of corresponding position id here
    List A Title and List B title are same i need each candidate info how can i do it
    Srinivas

    Hello,
    Still you have not told that whether Position id is there in listB or not. Anyway if Poistion id is not there in list B then you have to use Title column of listA to gete data from ListB. Look at sample code below. It will first get data from ListA,
    and use StringBuilder class to create dynamic CAML query because one Position id is having multiple values in listA.
    query.Query = "<Where><Eq><FieldRef Name='Postionid' /><Value Type='Lookup'>1</Value></Eq></Where>";
    SPListItemCollection items = list.GetItems(query);
    if(items.Count > 0)
    foreach(SPListItem item in items)
    string strTitle = Convert.Tostring(item["Title"]);
    //since listA is having multiple values for Postionid so you have to build a dynamic query here to get data from listB
    //Refer link to build dynamic query
    SPQuery listB = new SPQuery ();
    query.Query = stringbuilder;
    SPListItemCollection ListBitems = listB.GetItems(query);
    http://social.msdn.microsoft.com/Forums/sharepoint/en-US/2dfe5fd6-e556-4132-a35c-e9f240360307/issue-with-caml-query?forum=sharepointdevelopmentlegacy
    http://sharepoint.stackexchange.com/questions/69690/foreach-loop-inside-caml-query
    Above links will help you to create dynamic query (in your case you need to use multiple <OR> operator in listB.
    Hope it could help
    Hemendra:Yesterday is just a memory,Tomorrow we may never see
    Please remember to mark the replies as answers if they help and unmark them if they provide no help

  • SessionAttribute of array list

    Hi,
    I have a session attribute of an array list with class objects with different values. I know that if i wanted to cast this session attribute to a class i could do so if there were only one object. How do i find a particular object within the array list based on a attribute value so i can assign it to my class? If you have any suggestions, or places to read about this I'd appreciate it.
    Thanks!

    sorry for the confusion, i figured i'll just show the method that creates the array list and maybe then you'll understand. So once this is created i want to get a particular "account" out of the array list. :
    public static ArrayList<Account> selectAccounts()
            QbConnectionPool pool = QbConnectionPool.getInstance();
            Connection connection = pool.getConnection();
            PreparedStatement ps = null;
            ResultSet rs = null;
            String query = "SELECT ListID, Name, FullName, AccountNumber FROM Account";
            try
                ps = connection.prepareStatement(query);
                rs = ps.executeQuery();
                ArrayList<Account> accounts = new ArrayList<Account>();
                while (rs.next())
                {   Account account = new Account();
                    account.setListID(rs.getString(1));
                    account.setAccountName(rs.getString(2));
                    account.setFullName(rs.getString(3));
                    account.setAccountNumber(rs.getString(4));
                    accounts.add(account);
                return accounts;
            catch(SQLException e)
                e.printStackTrace();
                return null;
            finally
                DBUtil.closeResultSet(rs);
                DBUtil.closePreparedStatement(ps);
                pool.freeConnection(connection);
        }

Maybe you are looking for