Comparing Arraylist and String

Plz can anyone help me to find that this what will be the behaviour of this code.I have an Enumeration and and ArrayList.I want to comapre each object of Enumeration with each object of ArrayList.The code is
private boolean checkDeviceType(HttpServletRequest request){
          Enumeration e = request.getHeaderNames();
          String tmp = null;
          //String[] strKeys = null;
          ArrayList al = getValues("test");
          while(e.hasMoreElements()){
               tmp = (String)e.nextElement();
               for(int i = 0; i < al.size(); i++){
                    if(tmp.equalsIgnoreCase(al.toString()))// Ye line theek se check kar ki chalegi ya nahin
               return true;
          return false;
     }

Plz can anyone help me to find that this what will be
the behaviour of this code.I have an Enumeration and
and ArrayList.I want to comapre each object of
Enumeration with each object of ArrayList.The code
is
> private boolean checkDeviceType(HttpServletRequest
request){
          Enumeration e = request.getHeaderNames();
          String tmp = null;
          //String[] strKeys = null;
          ArrayList al = getValues("test");
          while(e.hasMoreElements()){
               tmp = (String)e.nextElement();
               for(int i = 0; i < al.size(); i++){
if(tmp.equalsIgnoreCase(al.get(i).toString()))// Ye line line theek se check kar ki chalegi ya nahin
               return true;
          return false;
     }You didn't extract the object from the ArrayList--so, your toString converts the whole ArrayList to a String, not just a single element. I fixed the line with your comment--added "get(i)."
Please use code tags (button above posting box) when posting code.

Similar Messages

  • Arraylist and string split help

    i want to add items from a textfile into an array list here is the txt file
    Title,Artist
    tester,test
    rest,test
    red, blue
    here is the code i am using
    try{
      FileReader fr = new FileReader(fileName);
    BufferedReader br = new BufferedReader(fr);
    String s;
    int c = 0;
    while((s = br.readLine()) != null) {
      c=c+1;
      CD c3 = new CD("");
      String tokens[] = s.split(",");
            for(String token : tokens) {
          System.out.println(c);
           System.out.println(tokens.toString());
              if ( c == 2){
                c3.setTitle(token);
                    System.out.println(c);
                     System.out.println(token);
             c = c+1;
                  if ( c == 3 ){
                    c3.setArtist(token);
                    discsArray.add(c3);
                      System.out.println(token);
                    c = 1;
              System.out.println(token); }}
    fr.close();
    }catch (Exception e){
          System.out.println("exception occurrred");
      }here is the output of the array
    title: tester artist: tester title: rest artist: tester title: red artist: red
    as you can see it misses the last line of the textfile and also doesnt display all of the separated string;
    thanks any help is appreciated

    thanks for ur help but that wasnt the problem
    i have fixed it however when its read all the lines
    an exception is always thrown
    everything works just crashes at the end
    any ideas
    try{
      FileReader fr = new FileReader(fileName);
    BufferedReader br = new BufferedReader(fr);
    String s;
    int c = 0;
    while((s = br.readLine()) != null) {
      c=c+1;
      CD c3 = new CD("");
      String tokens[] = s.split(",");
            for(String token : tokens) {        
              if ( c == 2){
                c3.setTitle(token); 
                      c = c+1;
              if ( c == 3 ){
                    c3.setArtist(token); 
           if ( c == 3 ){
                    discsArray.add(c3);
                    c = 1; 
    fr.close();
    br.close();
      }catch (Exception e){
          System.out.println("exception occurrred");
      }

  • Compare string and string from db

    I successfully queried a field from mysql into a jcombobox.
    What I can't figure out is why:
    String fromDB = comboBox.getSelectedItem().trim();
    AND
    String newString = "sameStringFromMySQL";are not equal. I already trimmed the text from the combo box but they are still not considered equal.
    WHY???

    just like how i described above.
    (fromDB.equals(newString)) returns false.
    Then they are not equal.
    Most likely reasons:
    -fromDB: This is starting with the text you think.
    -fromDB: You aren't getting it from the right place.
    -fromDB: You are modifying it before it gets to the comparison.
    -NewString: Doesn't have the value you think.
    -The comparison above isn't really the problem.
    You can always print the bytes in any string by using the getBytes() method on String and printing out both strings just before the above comparison (not elsewhere.)

  • Need help sorting an ArrayList of strings by an in common substring

    I'm trying to sort a .csv file, which I read into an ArrayList as strings. I would like to sort by the IP address within the string. Can someone please help me figure out the best way to sort these strings by a common substring each has, which is an IP address.
    I'm pretty sure that I need to use Collections some how, but I don't know where to begin with them besides trying to look online for help. I had no luck finding any good examples, so I came here as a last resort.
    Thanks for any help provided.

    You need to write your own Comparator class. In the compare() method you substring out the two IP addresses, compare them and return appropriate value. Then you call Collections.sort() and pass your list and comparator.

  • Regular expressions and string matching

    Hi everyone,
    Here is my problem, I have a partially decrypted piece string which would appear something like.
    Partially deycrpted:     the?anage??esideshe?e
    Plain text:          themanagerresideshere
    So you can see that there are a few letter missing from the decryped text. What I am trying to do it insert spaces into the string so that I get:
                        The ?anage? ?esides he?e
    I have a method which splits up the string in substrings of varying lengths and then compares the substring with a word from a dictionary (implemented as an arraylist) and then inserts a space.
    The problem is that my function does not find the words in the dictionary because my string is only partially decryped.
         Eg:     ?anage? is not stored in the dictionary, but the word �manager� is.
    So my question is, is there a way to build a regular expression which would match the partially decrypted text with a word from a dictionary (ie - ?anage? is recognised and �manager� from the dictionary).

    I wrote the following method in order to test the matching using . in my regular expression.
    public void getWords(int y)
    int x = 0;
    for(y=y; y < buff.length(); y++){
    String strToCompare = buff.substring(x,y); //where buff holds the partially decrypted text
    x++;
    Pattern p = Pattern.compile(strToCompare);
    for(int z = 0; z < dict.size(); z++){
    String str = (String) dict.get(z); //where dict hold all the words in the dictionary
    Matcher m = p.matcher(str);
    if(m.matches()){
    System.out.println(str);
    System.out.println(strToCompare);
    // System.out.println(buff);
    If I run the method where my parameter = 12, I am given the following output.
    aestheticism
    aestheti.is.
    demographics
    de.o.ra.....
    Which suggests that the method is working correctly.
    However, after running for a short time, the method cuts and gives me the error:
    PatternSyntaxException:
    Null(in java.util.regex.Pattern).
    Does anyone know why this would occur?

  • How to Sort JTable data using Multiple fields (Date, time and string)

    I have to fill the JTable data with some date, time and string values. for example my table data looks like this:
    "1998/12/14","15:14:38","Unicorn1","row1"
    "1998/12/14","15:14:39","Unicorn2","row2"
    "1998/12/14","15:14:40","Unicorn4","row3"
    "1998/12/17","12:14:12","Unicorn4","row6"
    Now the Sorted Table should be in the following way:
    "1998/12/17","12:14:12","Unicorn4","row6"
    "1998/12/14","15:14:40","Unicorn4","row3"
    "1998/12/14","15:14:39","Unicorn2","row2"
    "1998/12/14","15:14:38","Unicorn1","row1"
    ie First Date field should be sorted, if 2 date fields are same then sort based on time. if date and time fields are same then need to be sorted on String field.
    So if any one worked on this please throw some light on how to proceed. I know how to sort based on single column.
    But now i need to sort on multiple columns.So what is code change in the Comparater class.
    Thanks in advance.. This is urgent....

    I think your Schedule objects should implement Comparable. Then you can sort your linked list using the Collections.sort() method without passing in a Comparator.class Schedule(Date date, String class) implements Comparable
      public void compareTo(Object obj)
        Schedule other = (Schedule)obj;
        return date.getTime() - other.getDate().getTime();
    }

  • What to do when readString() fails and String[] out of bounds ?

    Dear Java People,
    I have a runtime error message that says:
    stan_ch13_page523.InvalidUserInputException: readString() failed. Input data is not a string
    java.lang.StringIndexOutOfBoundsException: String index out of range: 0
    below is the program
    thank you in advance
    Norman
    import java.io.*;
    import java.util.*;
    public class FormattedInput
        // Method to read an int value
        public int readInt()
          for(int i = 0; i < 2; i ++)
          if(readToken() == tokenizer.TT_NUMBER)
            return (int)tokenizer.nval;   // value is numeric so return as int
          else
            System.out.println("Incorrect input: " + tokenizer.sval +
               " Re-enter as integer");
            continue;         //retry the read operation
          } // end of for loop
          System.out.println("Five failures reading an int value" + " - program terminated");
          System.exit(1);  // end the program
          return 0;
         public double readDouble() throws InvalidUserInputException
           if(readToken() != tokenizer.TT_NUMBER)
              throw new InvalidUserInputException(" readDouble() failed. " + " Input data not numeric");
           return tokenizer.nval;
         public String readString() throws InvalidUserInputException
           if(readToken() == tokenizer.TT_WORD || ttype == '\"' ||  ttype == '\'')
            return tokenizer.sval;
           else
             throw new InvalidUserInputException(" readString() failed. " + " Input data is not a string");
           //helper method to read the next token
           private int readToken()
             try
               ttype = tokenizer.nextToken();
               return ttype;
             catch(IOException e)
               e.printStackTrace(System.err);
               System.exit(1);
              return 0;
           //object to tokenize input from the standard input stream
           private StreamTokenizer tokenizer = new StreamTokenizer(
                                                new BufferedReader(
                                                 new InputStreamReader(System.in)));
           private int ttype;                  //stores the token type code
    import java.io.*;
    import java.util.*;
    public class TryVectorAndSort
         public static void main(String[] args)
        Person aPerson;           // a Person object
        Crowd filmCast = new Crowd();
        //populate the crowd
        for( ; ;)
          aPerson = readPerson();
          if(aPerson == null)
            break;   // if null is obtained we break out of the for loop
          filmCast.add(aPerson);
        int count = filmCast.size();
        System.out.println("You added " + count + (count == 1 ? " person":  " people ") + "to the cast.\n");
        //Show who is in the cast using an iterator
         Iterator myIter = filmCast.iterator();
        //output all elements
        while(myIter.hasNext() )
          System.out.println(myIter.next());
        }//end of main
          //read a person from the keyboard
          static public Person readPerson()
         FormattedInput in = new FormattedInput();
            //read in the first name and remove blanks front and back
            System.out.println("\nEnter first name or ! to end:");
            String firstName = "";
            try
            firstName = in.readString().trim(); //read and trim a string
            catch(InvalidUserInputException e)
            e.printStackTrace(System.err);
            //check for a ! entered. If so we are done
            if(firstName.charAt(0) == '!')
              return null;
            //read the last name also trimming the blanks
            System.out.println("Enter last name:");
            String lastName= "";
            try
              lastName = in.readString().trim(); //read and trim a string
            catch(InvalidUserInputException e)
             e.printStackTrace(System.err);
            return new Person(firstName, lastName);
    //when I ran the program the output I received was:
    import java.io.StreamTokenizer;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.BufferedReader;
    public class InvalidUserInputException extends Exception
       public InvalidUserInputException() { }
          public InvalidUserInputException(String message)
              super(message);
    import java.util.*;
    class Crowd
      public Crowd()
        //Create default Vector object to hold people
         people = new Vector();
      public Crowd(int numPersons)
        //create Vector object to hold  people with given capacity
         people = new Vector(numPersons);
        //add a person to the crowd
        public boolean add(Person someone)
          return people.add(someone);
         //get the person at the given index
          Person get(int index)
          return (Person)people.get(index);
         //get the numbers of persons in the crowd
          public int size()
            return people.size();
          //get  people store capacity
          public int capacity()
            return people.capacity();
          //get a listIterator for the crowd
          public Iterator iterator()
            return people.iterator();
            //A Vector implements the List interface (that has the static sort() method
            public void sort()
              Collections.sort(people);
          //Person store - only accessible through methods of this class
          private Vector people;
    public class Person implements Comparable
      public Person(String firstName, String lastName)
        this.firstName = firstName;
        this.lastName = lastName;
      public String toString()
        return firstName + "  " + lastName;
       //Compare Person objects
        public int compareTo(Object person)
           int result = lastName.compareTo(((Person)person).lastName);
           return result == 0 ? firstName.compareTo(((Person)person).firstName):result;
      private String firstName;
      private String lastName;

    Dear Nasch,
    ttype is declared in the last line of the FormattedInput class
    see below
    Norman
    import java.io.*;
    import java.util.*;
    public class FormattedInput
        // Method to read an int value
        public int readInt()
          for(int i = 0; i < 2; i ++)
          if(readToken() == tokenizer.TT_NUMBER)
            return (int)tokenizer.nval;   // value is numeric so return as int
          else
            System.out.println("Incorrect input: " + tokenizer.sval +
               " Re-enter as integer");
            continue;         //retry the read operation
          } // end of for loop
          System.out.println("Five failures reading an int value" + " - program terminated");
          System.exit(1);  // end the program
          return 0;
         public double readDouble() throws InvalidUserInputException
           if(readToken() != tokenizer.TT_NUMBER)
              throw new InvalidUserInputException(" readDouble() failed. " + " Input data not numeric");
           return tokenizer.nval;
         public String readString() throws InvalidUserInputException
           if(readToken() == tokenizer.TT_WORD || ttype == '\"' ||  ttype == '\'')
             System.out.println(tokenizer.sval);
            return tokenizer.sval;
           else
             throw new InvalidUserInputException(" readString() failed. " + " Input data is not a string");
           //helper method to read the next token
           private int readToken()
             try
               ttype = tokenizer.nextToken();
               return ttype;
             catch(IOException e)
               e.printStackTrace(System.err);
               System.exit(1);
              return 0;
           //object to tokenize input from the standard input stream
           private StreamTokenizer tokenizer = new StreamTokenizer(
                                                new BufferedReader(
                                                 new InputStreamReader(System.in)));
           private int ttype;                  //stores the token type code
         }

  • Linked List and String Resources

    Linked Lists can be very slow when removing dynamic Strings.
    If you add and remove Strings in the
    following way, the performance is very poor:
    int n = 10000;
    long time = System.currentTimeMillis ();
    List list = new LinkedList();
    for (int i = 0 ; i < n ; i++)
    list.add ("" + n);
    for (int i = n-1 ; i >= 0 ; i--)
    list.remove(i/2);
    - If you add and remove the not dynamic String: "" + 10000 instead,
    - or do not remove the String (but add it in the middle),
    - or use a ArrayList
    the performance is much better.
    I suppose it depends on handling the String resources.
    If you run the following class, you will see what I mean:
    public class SlowLinkedList
    public static void main (String[] args)
    // Be carefull when accessing/removing Strings in a Linked List.
    testLinkedList ();
    testLinkedListHardCodedString();
    testLinkedListNoRemove();
    testArrayList();
    testArrayListNoParam();
    private static void testLinkedList ()
    int n = 10000;
    long time = System.currentTimeMillis ();
    List list = new LinkedList();
    for (int i = 0 ; i < n ; i++)
    list.add ("" + n);
    for (int i = n-1 ; i >= 0 ; i--)
    list.remove(i/2);
    time = System.currentTimeMillis () - time;
    System.out.println ("time dynamic String remove " + time);
    private static void testLinkedListHardCodedString ()
    int n = 10000;
    long time = System.currentTimeMillis ();
    List list = new LinkedList();
    for (int i = 0 ; i < n ; i++)
    list.add ("" + 10000);
    for (int i = n-1 ; i >= 0 ; i--)
    list.remove(i/2);
    time = System.currentTimeMillis () - time;
    System.out.println ("time same String remove " + time);
    private static void testLinkedListNoRemove ()
    int n = 10000;
    long time = System.currentTimeMillis ();
    List list = new LinkedList();
    for (int i = 0 ; i < n ; i++)
    list.add (i/2, "" + n);
    time = System.currentTimeMillis () - time;
    System.out.println ("time add dynamic String " + time);
    private static void testArrayList ()
    int n = 10000;
    long time = System.currentTimeMillis ();
    List list = new ArrayList();
    for (int i = 0 ; i < n ; i++)
    list.add ("" + n);
    for (int i = n-1 ; i >= 0 ; i--)
    list.remove(i/2);
    time = System.currentTimeMillis () - time;
    System.out.println ("time ArrayList " + time);
    private static void testArrayListNoParam ()
    int n = 10000;
    long time = System.currentTimeMillis ();
    List list = new ArrayList ();
    for (int i = 0 ; i < n ; i++)
    list.add ("" + 10000);
    for (int i = n-1 ; i >= 0 ; i--)
    list.remove(i/2);
    time = System.currentTimeMillis () - time;
    System.out.println ("time ArrayList same String " + time);
    A typic output of the Performance is:
    time dynamic String remove 1938
    time same String remove 312
    time add dynamic String 31
    time ArrayList 63
    time ArrayList same String 31

    begin long winded reply
    It doesn't matter if they are Strings or any other Object. LinkedList, in the way you are executing
    remove, is not effecient. The LinkList remove will look at the index, if it is less than the median
    it will start iterating from 0, if it is greater, it will start iterating in reverse from the end. Since you
    are removing from the median, it will always take the longest (either forward or backward) to
    get to the middle. Whereas, ArrayList simply uses the arraycopy to drop the element from the
    array. The "NoRemove" test doesn't make sense to me in relation to the others.
    Also, the VM is performing optimizations when you hardcode the 'n' value to 10000, it seems
    that the VM won't optimize when using 'n'. Tusing Integer.toString(n), instead of "" + n,
    in the first test case, it will yield better results.
    My profs in college drove collections into my head and removing from a linked list without
    an iterator is going to be inefficient. Iterators are a beautiful thing, use them.
    Try this code instead, it simulates your remove in the middle with an iterator and, on my
    machine, is faster than the ArrayList.
    private static void testLinkedList() {
        int n = 10000;
        long time = System.currentTimeMillis ();
        List list = new LinkedList();
        for (int i = 0 ; i < n ; i++) {
            list.add (Integer.toString(n));
        boolean forward = false;
        for (ListIterator li = list.listIterator(n >> 1); li.hasNext() || li.hasPrevious();) {
            if (forward) {
                li.next();
                forward = false;
            } else {
                li.previous();
                forward = true;
            li.remove();
        time = System.currentTimeMillis () - time;
        System.out.println ("time dynamic String remove " + time);
    }One other thing, run the tests more than once in a single VM and take the average. You could
    apply some statistical analysis to figure out which is better within a certain confidence percentage,
    but that is probably overkill. :)
    Check the collection tutorial for more info: http://java.sun.com/docs/books/tutorial/collections/implementations/general.html
    end long winded reply
    Matt

  • How to change elements in ArrayList into String

    Greetings,
    i like to change elements in arrayList into string.
    This is how i declare an ArrayList in a Java file
    ArrayList listing = new ArrayList();below is just a simple example of how i insert the string into the arraylist
    String concat = "';
    concat = concat + "apple";
    //Transfer the concat string into arraylist
    listing.add(concat);
    return listing;
    {code}
    On my Jsp page, it will receive the ArrayList from the java file. Lets say the Arrayist is pass into my JSP arraylist
    This is my JSP arraylist
    {code}ArrayList optLists = new ArrayList();{code}
    Inside the arraylist element, it holds data eg: *308577;;RS | [CAT 2] Level: Arena, Section: A02* with a pipe between RS and CAT 2.
    Now i looping the arraylist
    {code}int a = 0;
         for ( a=0; a < optLists.size(); a++)
              String tempString = "";
              String splitTemp = "";
                     String tempString = (String)optLists.get(a);
              splitTemp =  tempString.split("|");
              System.out.println("Split String Results: "+ splitTemp);
         {code}}
    Heres the error:
    *SeatAvailable_jsp.java:560: incompatible types*
        *[javac] found   : java.lang.String[]*
        *[javac] required: java.lang.String*
        *[javac]             splitTemp =  tempString.split("|");*
        *[javac]*       
    What can i do to solve the problem?
    Edited by: leeChaolan on May 2, 2008 4:45 AM
    Edited by: leeChaolan on May 2, 2008 4:48 AM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    paternostro is right, you are returning an array into a string which is wrong
    but try this, i haven't tested it though..
    nt a = 0;
         for ( a=0; a < optLists.size(); a++)
              String tempString = "";
              String splitTemp = "";
                     String tempString = (String)optLists.get(a);
              String[] splitTemp =  tempString.split("|");
              for(String xyz : splitTemp)
                   System.out.println("Split String Results: "+ xyz);
         }Edited by: linker on May 2, 2008 1:17 PM
    Edited by: linker on May 2, 2008 1:18 PM

  • Macro to compare CSV and Excel file

    Team,
    Do we have any macro to compare CSV and Excel file.
    1) In Excel we should have two text boxes asking the user to select the files from the path where they have Stored
    2) First Text is for CSV file
    3) Second Text box is for Excel file
    4) We Should have Compare button that should run the Macro and Show the Differences.
    Thanks!
    Kiran

    Hi
    Based on my understanding, we need to convert the 2 files into the same format before comparing two different formats files. 
    Here are the options:
    1. Convert the CSV file and Excel file into 2-dim Arrays, then compare them, about how to load a CSV file into VBA array, you can search it from
    internet or ask a solution in VBA forum.
    VBA forum:
    http://social.msdn.microsoft.com/Forums/en-US/home?forum=isvvba
    2. Also you can import CSV file to Excel sheet, and then compare them.
    Here is the sample code for your reference:
    ‘import csv file
    Sub InputCSV()
    Dim Wb As Workbook
    Dim Arr
    Set Wb = GetObject(Application.GetOpenFilename("csv file,*.csv", , "please choose a csv file", , False))
    Arr = Wb.ActiveSheet.Range("A1").CurrentRegion
    Wb.Close False
    Range("A1").Resize(UBound(Arr), UBound(Arr, 2)) = Arr
    End Sub
    ‘compare sheet
    Sub CompareTable()
    Dim tem, tem1 As String
    Dim text1, text2 As String
    Dim i As Integer, hang1 As Long, hang2 As Long, lie As Long, maxhang As Long, maxlie As Long
     Sheets("Sheet1").Select
    Columns("A:A").Select
    With Selection.Interior
    .Pattern = xlNone
    .TintAndShade = 0
    .PatternTintAndShade = 0
    End With
    Range("A1").Select
    Sheets("Sheet2").Select
    Rows("1:4").Select
    With Selection.Interior
    .Pattern = xlNone
    .TintAndShade = 0
    .PatternTintAndShade = 0
    End With
    Range("A1").Select
    MaxRow = 250
    MaxColumn = 40
    For hang1 = 2 To maxhang
    Dim a As Integer
    a = 0
    tem = Sheets(1).Cells(hang1, 1)
    For hang2 = 1 To maxhang
    tem1 = Sheets(2).Cells(hang2, 1)
    If tem1 = tem Then
    a = 1
    Sheets(2).Cells(hang2, 1).Interior.ColorIndex = 6
    For lie = 1 To maxlie
    text1 = Sheets(1).Cells(hang1, lie)
    text2 = Sheets(2).Cells(hang2, lie)
    If text1 <> text2 Then
            Sheets(2).Cells(hang2, lie).Interior.ColorIndex = 8
    End If
    Next
    End If
    Next
    If a = 0 Then
    Sheets(1).Cells(hang1, 1).Interior.ColorIndex = 5
    End If
    Next
    Hope this will help.
    Best Regards
    Lan
    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.
    Click
    HERE to participate the survey.

  • How do we compare a complex string?

    Hi guys,
    how do i compare the following strings
    input_Variable: User-agent : *
    if i want to ensure that the input_variable has "User-agent" and the character '*'.
    There are 3 possiblities for input_variable:
    1) User-agent: *
    2) disallow: http:///xxxxxxxxxxxx
    3) User-agent:Somename
    The white space between the words could be uneven and same goes with the character case.
    thanks,
    Derik

    Hi.. Derik
    How about this one..
    String input_Variable = "[from your input method]";
    if ( input_Variable.indexOf("User-agent") != -1
    && input_Variable.indexOf("*") != -1 )
    System.out.println("yeah.. authorized..");
    indexOf(String str) method returns -1 when it can't find out a specific string from the source string..

  • Converting ArrayList to String

    Hi ,
    I have ArrayList of String of size three. I want to make one string out of these three and also want to skip coma. I appreciate if any one can guide me.
    Thanks
    Panna

    So you have a list with "abc" "def" and "ghi" in it?
    And you want to get a single String "abcdefghi"?
    Then iterate over the list, append()ing each element to a StringBuffer.

  • Arraylists and arrays

    i'm trying to put the numbers in an arraylist into an int[] array. could anyone tell me how this could be done? i tried the below but i get an error pointing to return divisors.toArray();
    import java.util.ArrayList;
    import java.util.List;
    class FactorsDemo {
        public static void main(String[] args) {
         //for(int i = 10; i < 30; i+=5) {
             int[] divisors = getDivisors(10);
        static int[] getDivisors(int n) {
         List<Integer> divisors = new ArrayList<Integer>();
         for(int d = 1; d <= n/2; d++) {
             if(n%d == 0) divisors.add(new Integer(d));
         return divisors.toArray();
    }

    i'm trying to get this code to compile without using generics, just to see how it is done. it gets the divisors of a number, puts them into an arraylist, and then returns an array with those same divisors.
    i tried to cast the arraylist object to an int, but it's not working.
    can anyone show me what i need to do?
    import java.util.ArrayList;
    import java.util.List;
    class FactorsDemo2 {
        public static void main(String[] args) {
         for(int i = 10; i < 50; i+=5) {
             System.out.print("Factors of "+i+": ");
             int[] divisors = getDivisors(i);
             display(divisors);
        static int[] getDivisors(int n) {
         List divisors = new ArrayList();
         for(int d = 1; d <= n/2; d++) {
             if(n%d == 0) divisors.add(new Integer(d));
         int[] myInts = new int[divisors.size()];
            for(int i = 0; i < divisors.size(); i++) {
                   myInts[i] = (int) divisors.get(i);
            return myInts;
        static void display(int[] x) {
         for(int i = 0; i < x.length; i++) {
             System.out.print(x[i]+" ");
         System.out.println();
    }FactorsDemo2.java:21: inconvertible types
    found : java.lang.Object
    required: int
    myInts[i] = (int) divisors.get(i);
    ^
    Note: FactorsDemo2.java uses unchecked or unsafe operations.
    Note: Recompile with -Xlint:unchecked for details.
    1 error

  • Problem with Column types and String

    Hi
    I have some problem while comparing against empty string.
    My column is of type it_Linked_Button. Actually it seems that column type doesn't matter.
    If cell that belongs to this column is empty and based on other columns' values I put some value into this cell.
    It works fine.
    But when I clear that cell and try to put some value again nothing happens.
    In my if statement I'm checking against empty string and it fails second time.
    Before I put anything in that cell (in debugger) that value is "" so it is empty and it works.
    (OK, I see that after I posted this message it was slightly reformated)
    But after I put something and clear that cell and try to put something again (in debugger) I get "(here is some long space) " which fails String.IsNullOrEmpty(var) test.
    What is going on? Has it something to do with Column type?
    How to clear it so I can put something in it again?
    One more thing - to put values and clear it I use DbDataSource SetValue method. And String.Empty or ""(doesn't matter)
    Thanks
    Kamil
    NOTE
    I made some workaround that gives me the behaviour I want but still I would like to know what is going on?
    Edited by: Kamil Wydrzycki on Sep 24, 2009 12:57 PM

    DrLaszloJamf wrote:
    warnerja wrote:
    DrLaszloJamf wrote:
    1. Could you define an Enum? Then you could switch on enum values.
    2. Wait for Java 7 which is supposed to extend switch to strings?3. Put the target strings in a collection, write a loop to find the match in the collection and use the matching index in the switch statement. At least that will get rid of the hashcode kludge, where it won't mistakenly 'match' a string which isn't the actual target.3b: Map<String, Command>Yep.
    I also wanted to point this out to the OP:
    For example, let's say the 7 character string "BugABoo" happens to have the same hashcode as "EDI_DOC". And let's say your input just happens to have the string "BugABoo" in it, where you're extracting the 7 character substring. See the problem? You're getting "BugABoo" but treating it as if it really were "EDI_DOC", by virtue of comparing hashcodes instead of actual strings.
    OOPS!

  • Compare substrings in strings

    Not sure if this bit of code is what I'm suppose to be doing - hopefully someone can point me int he direction of the thing to think about
    ** Returns the number of times a given substring appears within the strings of a list of strings*
    ** @param listOfStrings the ArrayList that contains the strings to check*
    ** @param keyword the substring to find in each of the strings*
    ** @return the number of times keyword appear in the strings listed in listOfStrings*
    public int keywordCount(ArrayList listOfStrings, String keyword) {
         int counter;
         for(int i = 0; i < listofStrings.size(); i ++){
              if (listofStrings.get[i] == keyword){
                   counter += 1;
              return System.out.println("keyword appears " + counter " " times.");     
    }{code}                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    return System.out.println("keyword appears " + counter " " times.");
    {code}
    You either return something or print something to the console. Don't do both. Also, see how the end bracket and semicolon are red. That means you have made an error with your formatting.
    I'd say you would need nested loops. Outer loop to iterate over your list of Strings. Inner loop to iterate over each string to see how many times the substring exists in that String.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

Maybe you are looking for

  • Problem with inserting a row in the current table

    I am working on Html editor using swings. actually i am trying to insert a row using private void insertTableRow(int cols)           StringBuffer sRow = new StringBuffer();           sRow.append("<TR>");           for(int i = 0; i < cols; i++)       

  • Special Characters in Thesaurus

    I have a requirement to be able search on all variations of a name. I tried using the RT tag in a thesaurus which worked for names without special characters. The names I need to search on include quotes and dashes. I have not been able to come up wi

  • TOMCAT - Enable Server Side Includes

    Hi, i tried to include files in my pages using <!--#include file="file_name"--> but its not working so i suppose i must configure my tomcat in some way in order to enable the server side includes (im tottaly new to TOMCAT) so, anyone can explain me h

  • How do I activate a new device for ADE?

    Says I have too many activated....most are old readers I have replaced and updated

  • Setting AE with Ethernet cable

    Sorry for my English. After a week of pain, I've just downgraded from a n network (Time Capsule + AXn) to my old, reliable AEg + AXg network. The problem is that now the Airport Utility 5.3.2 let me configure the devices by ethernet cable only. Well,