Get Object[] length in ArrayList

How do I get the size of the Object[] in ArrayList?
Not ArrayList.size() which returns how many Elements
are in the List.

You could use reflection if you really wanted to know
how much memory you have "wasted".
KajHere's a stupid class to do just that.
Thanks.
import java.util.*;
import java.lang.reflect.*;
public class Test{
public static void main(String[] args){
     new Test();
public Test(){
     List list = new ArrayList(1);
     double capacity = 0;
     double size = 0;
     Random rand = new Random();
     int iter = rand.nextInt(100);
     System.out.println("Iter: " + iter);
     for(int i = 0; i < iter; i++){
     int rn = rand.nextInt(10);
     Integer integer = new Integer(rn);
     list.add(integer);
     size = list.size();
     System.out.println("List Size: " + size);
     try{
     Class al = list.getClass();
     // Get Declared Fields
     System.out.println("\nGet Declared Fields");
     Field[] fields1 = al.getDeclaredFields();
     for(int i = 0; i < fields1.length; i++){
     System.out.println("Field: " + fields1.getName());
     // Get Fields
     System.out.println("\nGet Fields");
     Field[] fields2 = al.getFields();
     for(int i = 0; i < fields2.length; i++){
     System.out.println("Field: " + fields2[i].getName());
     // Get Field
     System.out.println("\nGet Field");
     //Field field = al.getField("elementData");
     Field field = fields1[1];
     field.setAccessible(true);
     System.out.println("Field (elementData): " + field.getName());
     Object obj = field.get(list);
     Object[] elementData = (Object[])obj;
     capacity = elementData.length;
     } catch(Exception e){
     e.printStackTrace();
System.out.println("List Capacity: " + capacity);
     int percentOver = (int)(((capacity - size) / capacity) * 100);
System.out.println("Percent Over: " + percentOver);

Similar Messages

  • Get objects out of Arraylist

    Hi I have this code, below, The set methods in the class Website work just fine to get the data into the arraylist, but i just can't figure out the get methods to get the objects back out to compare. Could someone please help. i'm almost finished with this thing!!
    Iterator itr1 = Websites1.iterator();
    Iterator itr2 = Websites2.iterator();
    outer: while (itr1.hasNext()) {
    while (itr2.hasNext()) {
    //Object site1 = new Object ();
    //Object site2 = new Object ();
    Object site1 = (Website)itr1.next();
    content1 = site1.getCon();
    date1 = site1.getMod();
    Object site2 = (Website)itr2.next();
    content2 = site2.getCon();
    date2 = site2.getMod();
    if (date1 != date2 ) {
    if (content1 != content2)
    alert.play();
    //do other stuff//
    else;
    else;
    continue outer;
    class Website {
    public String WebsiteName, WebsiteContent, Content;
    public Date LastModified, Modified;
    public Website() {
    WebsiteName = "";
    WebsiteContent = "";
    LastModified = null;
    public Website (String Name, String Content, Date Modified) {
    WebsiteName = Name;
    WebsiteContent = Content;
    LastModified = Modified;
    public void setName(String Name) {
    WebsiteName = Name;
    public void setContent(String Content) {
    WebsiteContent = Content;
    public void setModified(Date Modified) {
    LastModified = Modified;
    public String getCon() {
    Content = WebsiteContent;
    public Date getMod() {
    Modified = LastModified;

    I think that worked (duh i should have noticed it earlier), but now i'm getting a real weird error when i try to compile on my custom get methods
    missing return statement
    public String getCon() {//(points to this)
    and the same thing on the public Date getMod() method
    any ideas?
    I'm lost now i've never seen that before

  • How to create and object from an arrayList

    Hi I want to create an object from an arrayList.
    here is my code...
    BillingQueryParam billingQueryParam = new BillingQueryParam();
    /*This BillingQueryParam and billingItemManagerActionForm has getter and setter method for following attributes.
    private int billingItemId;
    private String[] paramName;
    private String[] defaultParamValue;
    List billingQueryParamList = new ArrayList();               
    for(int i = 0; i < billingItemManagerActionForm.getParamName().length; i++) {
         billingQueryParam.setParamName(billingItemManagerActionForm.getParamName());
    for(int i = 0; i < billingItemManagerActionForm.getDefaultParamValue().length; i++) {
      billingQueryParam.setDefaultParamValue(billingItemManagerActionForm.getDefaultParamValue());
         billingQueryParam.setBillingItemId(billingItem.getBillingItemId());
         billingQueryParamList.add(billingQueryParam);
    System.out.println("****** ArrayList Size-->"+billingQueryParamList.size());
    for (Iterator iter = billingQueryParamList.iterator();iter.hasNext();) {
         billingQueryParam = (BillingQueryParam)iter.next();
          System.out.println("****** BillingItemId-->"+billingQueryParam.getBillingItemId());
          System.out.println("****** Param Name-->"+billingQueryParam.getParamName()); //printing an array of paramName
          System.out.println("****** Default param value-->"+billingQueryParam.getDefaultParamValue());
    }Here after iterating this list I want to create an object of billingQueryParam which contains a single value of itemId, paramName,paramTypeId and defaultParamName and I want to persist this object in database.
    Please help...!!!
    Thanks

    Now this is too much.. Do i need to tell this thing to u as well. How did u come to this forum?
    Can't u see link to Java programming forum at the top.

  • Removing a object from an arraylist

    hi,
    i am putting an object into an arraylist like:
    <code>
    Hashtable userList = new Hashtable();
    userList = this.loadUsers();
    boolean found = false;
    //look for the user in the list
    for(int i = 0; i< userList.size(); i++)
    User user = new User();
    user = (User)userList.get(""+i);
    if (user.userName.equalsIgnoreCase(userName) && user.password.equalsIgnoreCase(password))
    try
    found = true;
    clientList.add(user);
    System.out.println(userName);
    catch (Exception e)
    e.printStackTrace();
    <\code>
    and removing it like this:
    <code>
    Hashtable userList = new Hashtable();
    userList = this.loadUsers();
    boolean found = false;
    //look for the user in the list
    for(int i = 0; i< userList.size(); i++)
    User user = new User();
    user = (User)userList.get(""+i);
    System.out.println(user);
    if (user.userName.equalsIgnoreCase(userName))
    try
    found = true;
    //add the logged in user to the Arraylist
    int arraylist = clientList.size();
    System.out.println(user);
    System.out.println("client removed = "+clientList.remove(user));
    System.out.println(userName);
    catch (Exception e)
    e.printStackTrace();
    <\code>
    however the object reference is not the same when i take it out so it wont remove... why?
    Assignment.ChatImp$User@11121f6
    Assignment.ChatImp$User@f7f540

    This code is brain dead.
    Looks like your User class has public data members. True?
    Why are you using a Hashtable when you appear to want a List?
    You probably don't override equals and hashcode for your object.
    Try this:
    package user;
    import java.io.Serializable;
    import java.util.List;
    import java.util.ArrayList;
    * Created by IntelliJ IDEA.
    * User: Michael
    * Date: Dec 2, 2006
    * Time: 9:59:11 AM
    * To change this template use File | Settings | File Templates.
    public class User implements Serializable
        private String username;
        private String password;
        public static void main(String[] args)
            if (args.length > 0)
                List<User> users = new ArrayList<User>(args.length);
                User userToRemove = new User(args[0], args[0]);
                for (int i = 0; i < args.length; ++i)
                    User u = new User(args, args[i]);
    users.add(u);
    System.out.println("before: " + users);
    System.out.println("users " + (users.contains(userToRemove) ? "" : "does not ") + "contain " + userToRemove);
    users.remove(userToRemove);
    System.out.println("after : " + users);
    System.out.println("users " + (users.contains(userToRemove) ? "" : "does not ") + "contain " + userToRemove);
    private User()
    this("", "");
    public User(String username, String password)
    if ((username == null) || "".equals(username.trim()))
    throw new IllegalArgumentException("username cannot be blank or null");
    if ((password == null) || "".equals(password.trim()))
    throw new IllegalArgumentException("password cannot be blank or null");
    this.username = username;
    this.password = password;
    public String getUsername()
    return username;
    public String getPassword()
    return password;
    public boolean equals(Object o)
    if (this == o)
    return true;
    if (o == null || getClass() != o.getClass())
    return false;
    User user = (User) o;
    if (password != null ? !password.equals(user.password) : user.password != null)
    return false;
    if (username != null ? !username.equals(user.username) : user.username != null)
    return false;
    return true;
    public int hashCode()
    int result;
    result = (username != null ? username.hashCode() : 0);
    result = 31 * result + (password != null ? password.hashCode() : 0);
    return result;
    public String toString()
    return new StringBuilder().append("User{").append("username='").append(username).append('\'').append(", password='").append(password).append('\'').append('}').toString();

  • How can u get the Length of a file u are going to download?

    HI,<br>
    I have another question, is it possible that u can get the length of a file which u are just going to download?<br>
    <br>
    I have the following code example:<br>
    <br>url = new URL(dlfrom);<br>
    f=new File(url.toURI());<br>
    System.out.println(f.length)();<br><br>
    unfortunatly it keeps throwing an exception, please help.

    RTFM
    http://java.sun.com/j2se/1.5.0/docs/api/java/net/URLCo
    nnection.html#getContentLength()<br>
    I tried to apply your sollution, but it is allways returning -1, so what should I do now, is there any possebility still to get the length of the object, because i thought of doing something similar as a tool to download stuff

  • Getting items out of arrayList

    Hi everyone
    I have the following scenario:
    Have two java class files which gets used to extract data from database and a jsp which display data.
    I get the data out of the database, but my problem is displaying it correctly using the jsp which uses JSTL.
    The ContactsData.class file extracts the data out of the database and puts it in the Contacts.class class which then gets written to an arraylist which stores the Contacts.class and then returns the ArrayList to the requester.
    Here is the code, can someone please help me to manipulate the arraylist to display the right info.
    Contacts.class which holds the contacts.
    package contacts;
    import java.io.Serializable;
    import java.util.*;
    public class Contacts implements Serializable
         //String varialbes to store the details about the contact
         private String contactName,company, workNumber, cellNumber, faxNumber, email,country;
         //contacts constructor
         public Contacts()
         //method to set the company
         public void setCompany(String company)
              this.company = company;
         //method to set the Contact name
         public void setContactName(String contactName)
              this.contactName = contactName;
         //method to set the work teletphone number
         public void setWorkNumber(String workNumber)
              this.workNumber = workNumber;
         //method to set the cellphone number
         public void setCellNumber(String cellNumber)
              this.cellNumber = cellNumber;
         //method to set the fax number
         public void setFaxNumber(String faxNumber)
              this.faxNumber = faxNumber;
         //method to set the email
         public void setEmail(String email)
              this.email = email;
         //method to set the country
         public void setCountry(String country)
              this.country = country;
         //method to get the company
         public String getCompany()
              return company;
         //method to get the contact name
         public String getContactName()
              return contactName;
         //method to get the work telephone number
         public String getWorkNumber()
              return workNumber;
         //method to get the cellphone number
         public String getCellNumber()
              return cellNumber;
         //method to get the fax number
         public String getFaxNumber()
              return faxNumber;
         //method to get the email
         public String getEmail()
              return email;
         //method to get the country
         public String getCountry()
              return country;
    }piece of the contactsData.class class which retrieves the data out of the database and stores it in Contacts.class class and then store the Contacts class in the arrayList which gets returned to the requester.
         public ArrayList getContactList()
              //arrayList to hold the contacts
              contactList = new ArrayList<Contacts>();
              try
                   ResultSet rs = stmt.executeQuery("SELECT * FROM Contacts");     //selecting from the database
                   while(rs.next())
                        //creating contacts object
                        contact = new Contacts();
                        //adding details to the Contacts object
                        contact.setContactName(rs.getString(1));
                        contact.setCompany(rs.getString(2));
                        contact.setWorkNumber(rs.getString(3));
                        contact.setCellNumber(rs.getString(4));
                        contact.setFaxNumber(rs.getString(5));
                        contact.setEmail(rs.getString(6));
                        contact.setCountry(rs.getString(7));
                        //adding Contacts object to the Arraylist
                        contactList.add(contact);
              catch(SQLException se)
                   System.out.println("Could not retrieve contacts");
              return contactList;     //returning the arraylist
         }The jsp that need to display the contacts within the arraylist, which I don't get right.
    <?xml version="1.0"?>
    <%@ page import="contacts.Contacts"%>
    <%@ page import="java.util.*"%>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
    <jsp:useBean id = "contactsData" scope = "page" class ="contacts.ContactsData"/>
    <html>
         <head>
              <title>Contact List</title>
              <meta http-equiv="cache-control" content="max-age=0, must-revalidate, no-cache, no-store, private">
              <meta http-equiv="expires" content="-1">
              <meta http-equiv="pragma" content="no-cache">
              <script language=JavaScript>
              <!--
                   function clicked(clickedValue)
                        if(clickedValue == "add")
                             window.location = "AddContact.jsp";
              -->
              </script>
         </head>
              <body>
              <h1>Contacts</h1>
              <form>
                   <table cellpadding="5">
                   <c:forEach var="contacts" items="${contactsData.contactList}"> //getting the list from the ContactData class
                        <tr>
                        <td><input type="radio" name="deleteContact" value="${contacts.company}"></td> //want to display the company name from the contacts
                        </tr>
                   </c:forEach>
                   </table>
                        <br>
                        <input type="button" value="Add" onClick="clicked('add')"/>
                        <input type="submit" value="Delete" onClick="clicked('del')"/>
              </form>
         </body>
    </html>

    HI, we need to specify the scope we used,In my Ex its request
    so my forEach tag ..
    <c:forEach var="stud" items="${requestScope.studli}">
    <c:out value="${stud.SID}"></c:out>
    <c:out value="${stud.SNAME}"></c:out>
    </c:forEach>

  • PowerShell: Want to get the length of the string in output

    Hi All,
    I am typing this but it is not working. Does anyone know what I could be doing wrong.
    The command I wrote is:
                         GCI -file  | foreach {$_.name} | sort-object length | format-table name, length
    But it is not working. I am expecting a name of the file and length of the string like 8 characters etc. my file is called mystery so it should have 7 as its output of the name, length.
    Thank-you
    SQL 75

    Get-ChildItem supports both  -File and -Directory.
    Help will help:
    https://technet.microsoft.com/library/hh847897(v=wps.630).aspx
    Read the first couple of parameters to see.
       GCI -file  | sort-object length | format-table name, length | ft -auto
    Seems to be a rasher of bad answers to day.  YOu were just extracting the name property then trying to sort on a property that doesn't exist.
    Do the sort first then select the properties.
    it helps to test answers before posting.  I know because I get bit by posting without thinking to often.  I have to remember to think first.
    ¯\_(ツ)_/¯

  • Map.get(K) and Map.get(Object)

    When I first saw the new 2.0 generics compiler, I was very pleased to see that the signature of Map.get() has changed (since 1.3) from:
        interface Map<K,V> { V get(Object obj); }to:
        interface Map<K,V> { V get(K key); }because it means buggy code like this:
        Map<File,Integer> fileSizeMap = new HashMap<File,Integer>();
        Integer sizeOfFile = fileSizeMap.get("/tmp/foo");
        if (sizeOfFile == null) {
            System.err.println("File not found in map");
        }(where I have mistakenly called Map.get() with a String rather than a File) will now get a compiler error rather than a fault raised several months after the application has gone live.
    So, as I say, I am very pleased with the new signature for Map.get(), although I would also like to see the following methods changed:
        boolean containsKey(Object)   -> boolean containsKey(K)
        boolean containsValue(Object) -> boolean containsValue(V)
        V remove(Object object)       -> V remove(K)However, I just read on http://cag.lcs.mit.edu/~cananian/Projects/GJ/Bugs/v20/map.html that Neal Gafter says that putting Map.get(K) into 2.0 was a mistake, and that it will be put back to Map.get(Object) in the next version.
    I do hope I haven't missed something obvious, but keeping these methods with Object parameters seems to me to be a backwards step from the excellent type safety benefits provided by Generics.
    Does anyone else agree with me that having get(K) would be beneficial in allowing the compiler to identify bugs that would otherwise only be discovered much later?
    Or, could someone explain to me why having get(Object) is preferable, and whether this reason is more important than the type safety issue I identified in my example code above?
    Many thanks in advance
    Geoff

    Gafter wrote:
    The reason the argument type is Object and not K is that existing code depends on the fact
    that passing the "wrong" key type is allowed, causes no error, and simply results in the
    key not being found in the map.But "existing code" does not use Generics, and therefore as with all other non-generic code, the authors of that code can choose to either leave it as it is (in which case their Maps will become Map<Object,Object> and Map.get() will then take an Object), or to upgrade it to Generics, and take advantage of the helpful compiler messages that may highlight some design flaws in the original code.
    In Jakarta Commons Collections (this is "existing code"), there's a class MultiHashMap which extends HashMap. When you call MultiHashMap.put(someKey, someValue) it appends someValue to an ArrayList that gets stored as the value in the HashMap. However when you call MultiHashMap.get(someKey), it returns a Collection of values, rather than just a single value.
    If they try to upgrade MultiHashMap to Generics, they are going to come up with a problem: they would be needing something like this:
        public class MultiHashMap<K,V> extends HashMap<K,V> {
            public V put(K key, V value) { ... }
            public Collection<V> get(K key) { ... }
        }which of course is not allowed, since Map<K,V>.get() returns V, not Collection<V>.
    Now, I don't hear anyone saying: This "existing code" relies on Map.get() returning an Object, so in Generics we're going to make Map.get() return Object rather than V.
    No, instead we (correctly) say: That MultiHashMap code was wrong to abuse the flexibility provided by the use of Object as the return value of Map.get(), and if it wishes to use Generics, it will either need to become MultiHashMap<K,Object>, or if it insists on being MultiHashMap<K,V>, it will not be allowed to extend HashMap.
    I really don't see the problem in using Generics (and a typesafe Java Collections API) as a means of highlighting problems in existing code. As I said before, existing code will continue to work as before, because List will become List<Object> and Map will become Map<Object,Object>.
    This is no worse than "accidentally" trying to get() with a key of the right
    type but the wrong value. Since none of these methods place the key into the
    map, it is entirely typesafe to use Object as the method's parameter.Suppose for a moment that when String.endsWith() was first written, it took an Object parameter instead of a String. If I were to say to you: This method needs to change its parameter from Object to String, would you tell me that that there's no need to make the change, because a String can only ever end in a String, and so it is entirely typesafe to use Object as the method's parameter?
    Geoff

  • Arraylist issue: pass all the arrayList `s object to other arrayList ...

    hi all...i hope somebody could show me some direction on my problem...i want to pass a arraylist `s cd information to an other arraylist
    and save the new arraylist `s object to a file...i try to solve for a long ..pls help...
    import java.text.*;
    import java.util.*;
    import java.io.*;
    public class Demo{
         readOperation theRo = new readOperation();
         errorCheckingOperation theEco = new errorCheckingOperation();
         ArrayList<MusicCd>  MusicCdList;
         private void heading()
              System.out.println("\tTesting read data from console, save to file, reopen that file\t");
         private void readDataFromConsole()
         //private void insertCd()
            MusicCdList = new ArrayList<MusicCd>( ); 
            MusicCd theCd;
            int muiseCdsYearOfRelease;
            int validMuiseCdsYearOfRelease;
            String muiseCdsTitle;
              while(true)
                    String continueInsertCd = "Y";
                   do
                        muiseCdsTitle = theRo.readString("Please enter your CD`s title : ");
                        muiseCdsYearOfRelease = theRo.readInt("Please enter your CD`s year of release : ");
                        validMuiseCdsYearOfRelease = theEco.errorCheckingInteger(muiseCdsYearOfRelease, 1000, 9999);
                        MusicCdList.add(new MusicCd(muiseCdsTitle, validMuiseCdsYearOfRelease));//i try add the cd`s information to the arrayList
                        MusicCdList.trimToSize();
                        //saveToFile(MusicCdList);
                        continueInsertCd = theRo.readString("Do you have another Cd ? (Y/N) : ");
                   }while(continueInsertCd.equals("Y") || continueInsertCd.equals("y") );
                   if(continueInsertCd.equals("N") || continueInsertCd.equals("n"));
                                                    //MusicCdList.add(new MusicCd(muiseCdsTitle, muiseCdsYearOfRelease));                              
                        break;
                      //System.out.println("You `ve an invalid input " + continueInsertCd + " Please enter (Y/N) only!!");
         //i want to pass those information that i just add to the arrayList to file
         //I am going to pass the arraylist that contains my cd`s information to new arraylist "saveitems and save it to a file...
         //i stuck on this problem
         //how do i pass all the arrayList `s object to another arraylist ..pls help
         //it is better show me some example how to solve thx a lot
         private void saveToFile(ArrayList<MusicCd> tempItems)
              ArrayList<MusicCd> saveItems;
              saveItems = new ArrayList<MusicCd>();
              try
                   File f = new File("cdData.txt");
                   FileOutputStream fos = new FileOutputStream(f);
                   ObjectOutputStream oos = new ObjectOutputStream(fos);
                   saveItems.add(ArrayList<MusicCd> tempItems);
                   //items.add("Second item.");
                   //items.add("Third item.");
                   //items.add("Blah Blah.");
                   oos.writeObject(items);
                   oos.close();
              catch (IOException ioe)
                   ioe.printStackTrace();
              try
                   File g = new File("test.fil");
                   FileInputStream fis = new FileInputStream(g);
                   ObjectInputStream ois = new ObjectInputStream(fis);
                   ArrayList<String> stuff = (ArrayList<String>)ois.readObject();
                   for( String s : stuff ) System.out.println(s);
                   ois.close();
              catch (Exception ioe)
                   ioe.printStackTrace();
         public static void main(String[] args)
              Demo one = new Demo();
              one.readDataFromConsole();
              //one.saveToFile();
              //the followring code for better understang
    import java.io.Serializable;
    public class MusicCd implements Serializable
         private String musicCdsTitle;
            private int yearOfRelease;
         public MusicCd()
              musicCdsTitle = "";
              yearOfRelease = 1000;
         public MusicCd(String newMusicCdsTitle, int newYearOfRelease)
              musicCdsTitle = newMusicCdsTitle;
              yearOfRelease = newYearOfRelease;
         public String getTitle()
              return musicCdsTitle;
         public int getYearOfRelease()
              return yearOfRelease;
         public void setTitle(String newMusicCdsTitle)
              musicCdsTitle = newMusicCdsTitle;
         public void setYearOfRelease(int newYearOfRelease)
              yearOfRelease = newYearOfRelease;
         public boolean equalsName(MusicCd otherCd)
              if(otherCd == null)
                   return false;
              else
                   return (musicCdsTitle.equals(otherCd.musicCdsTitle));
         public String toString()
              return("Music Cd`s Title: " + musicCdsTitle + "\t"
                     + "Year of release: " + yearOfRelease + "\t");
         public ArrayList<MusicCd> getMusicCd(ArrayList<MusicCd> tempList)
              return new ArrayList<MusicCd>(ArrayList<MusicCd> tempList);
    import java.util.Scanner;
    import java.util.InputMismatchException;
    import java.util.NoSuchElementException;
    public class errorCheckingOperation
         public int errorCheckingInteger(int checkThing, int lowerBound, int upperBound)
               int aInt = checkThing;
               try
                    while((checkThing < lowerBound ) || (checkThing > upperBound) )
                         throw new Exception("Invaild value....Please enter the value between  " +  lowerBound + " & " +  upperBound );
               catch (Exception e)
                 String message = e.getMessage();
                 System.out.println(message);
               return aInt;
           public int errorCheckingSelectionValue(String userInstruction)
                int validSelectionValue = 0;
                try
                     int selectionValue;
                     Scanner scan = new Scanner(System.in);
                     System.out.print(userInstruction);
                     selectionValue = scan.nextInt();
                     validSelectionValue = errorCheckingInteger(selectionValue , 1, 5);
               catch (NoSuchElementException e)
                   //if no line was found
                   System.out.println("\nNoSuchElementException error occurred (no line was found) " + e);
              catch (IllegalStateException e)
                   // if this scanner is closed
                   System.out.println("\nIllegalStateException error occurred (scanner is closed)" + e);
              return validSelectionValue;
    import java.util.*;
    public class readOperation{
         public String readString(String userInstruction)
              String aString = null;
              try
                         Scanner scan = new Scanner(System.in);
                   System.out.print(userInstruction);
                   aString = scan.nextLine();
              catch (NoSuchElementException e)
                   //if no line was found
                   System.out.println("\nNoSuchElementException error occurred (no line was found) " + e);
              catch (IllegalStateException e)
                   // if this scanner is closed
                   System.out.println("\nIllegalStateException error occurred (scanner is closed)" + e);
              return aString;
         public char readTheFirstChar(String userInstruction)
              char aChar = ' ';
              String strSelection = null;
              try
                   //char charSelection;
                         Scanner scan = new Scanner(System.in);
                   System.out.print(userInstruction);
                   strSelection = scan.next();
                   aChar =  strSelection.charAt(0);
              catch (NoSuchElementException e)
                   //if no line was found
                   System.out.println("\nNoSuchElementException error occurred (no line was found) " + e);
              catch (IllegalStateException e)
                   // if this scanner is closed
                   System.out.println("\nIllegalStateException error occurred (scanner is closed)" + e);
              return aChar;
         public int readInt(String userInstruction) {
              int aInt = 0;
              try {
                   Scanner scan = new Scanner(System.in);
                   System.out.print(userInstruction);
                   aInt = scan.nextInt();
              } catch (InputMismatchException e) {
                   System.out.println("\nInputMismatchException error occurred (the next token does not match the Integer regular expression, or is out of range) " + e);
              } catch (NoSuchElementException e) {
                   System.out.println("\nNoSuchElementException error occurred (input is exhausted)" + e);
              } catch (IllegalStateException e) {
                   System.out.println("\nIllegalStateException error occurred (scanner is closed)" + e);
              return aInt;
    }

    sorry for my not-clear descprtion...thc for your help....i got a problem on store some data to a file ....u can see my from demo..
    Step1: i try to prompt the user to enter his/her cd `s information
    and i pass those cd `s information to an object "MuiscCd" ..and i am going to add this "MuiscCd" to the arrayList " MusicCdList ". i am fine here..
    Step2: and i want to save the object that `s in my arrayList " MusicCdList " to a file....i got stuck here..<_> ..(confused).
    Step3:
    i will reopen the file and print it out..(here i am alright )

  • Nulls from HashMap.get(Object)

    I understand that I get the nulls because the Object is not in the map. But is there some elegant way to have it default to the empty String?
    Right now, after I grab all my data into variable with HashMap.get(Object), I go and check each once for null, and assign it the empty String instead. This is a lot of lines of code for something that is so basic.
    I know i could initialize them all to the empty string, and then for each variable, check the HashMap with containsKey(Object) before assigning with HashMap.get(Object). Now, would I be correct in assuming the compiler would optimize this for me and not actually check the HashMap twice for the same Object? And... even if that is the case, its still just as many lines of code.
    Is there perhaps some more elegant way?
    String exchange = parameterMap.get("exchange");
    String messageType = parameterMap.get("messagetype");
    String traderTimeStamp = parameterMap.get("traderTimeStamp");
    String exchangeTimeStamp = parameterMap.get("exchangeTimeStamp");
    String sequence = parameterMap.get("sequence");
    String product = parameterMap.get("product");
    String quantity = parameterMap.get("quantity");
    String price = parameterMap.get("price");
    if (exchange == null)
    exchange = "";
    if (messageType == null)
    messageType = "";
    if (traderTimeStamp == null)
    traderTimeStamp = "";
    if (exchangeTimeStamp == null)
    exchangeTimeStamp = "";
    if (sequence == null)
    sequence = "";
    if (product == null)
    product = "";
    if (quantity == null)
    quantity = "";
    if (price == null)
    price = "";

    You could first put "" for all potential keys.
    Or you could create a helper method
    public String nonNull(String s) {
      return (s != null) ? s : "";
    String exchange = nonNull(parameterMap.get("exchange"));

  • How to get the length of a field value, not the length of DB's CHAR(20)

    Hello.
    I'm trying to handle a String from my DataBase and get its length:
    String myName;
    int i;
    PreparedStatement sql = Conn.prepareStatement("SELECT NAME FROM MY_TABLE");
    ResultSet results = sql.executeQuery();
    results.next();
    myName = results.getString("NAME");
    i = myName.length();
    out.println("The value is " + myName + " and the length is " + String.valueOf(i) );
    I get:
    " The value is Tom and the lengh is 20 "
    20 is the length of the field (it's a CHAR (20) ), but I would like to get the length
    of 'Tom'.
    On other hand, I would like to detect if this value is 'Tom' or not, but trying with:
    if (myName.equals("Tom")) {...}
    or
    if (myName == "Tom") {...}
    There is no response.
    Any experience?

    myName = results.getString("NAME");
    if(myName!=null) myName = myName.trim(); //Take out trailing spaces
    i = myName.length();Sudha

  • How to get object key before load data into form?

    I need to get object key (e.g. ItemCode in Item Master Data From ,docEntry in A/R Invoice From) to calculate and do something  before data is loaded into this form .
    I try to use SAPbouiCOM.BusinessObjectInfo.objectKey as in this code.
    Private Sub oApp_FormDataEvent(ByRef pVal As SAPbouiCOM.BusinessObjectInfo, ByRef BubbleEvent As Boolean) Handles oApp.FormDataEvent
           If pVal.FormTypeEx = "672" And pVal.BeforeAction = True And pVal.EventType = SAPbouiCOM.BoEventTypes.et_FORM_DATA_LOAD Then
                   oApp.MessageBox(pVal.ObjectKey)
           End If
    End Sub
    But this fields doesn't valid under this condition (form DI help file).
    - The property returns an empty value in the before notification of the Load action (et_FORM_DATA_LOAD) triggered by a Find operation.
    How can I get this value(key)?

    Janos
    I can't do a calculation after data is loaded because what I'm going to do is that if the opening entry match my condition , the system will not let that user see that entry (bubbleEvent = False).
    I think when formDataEvent is triggered B1 know which entry are going to load because before this event is triggered we did one of following ways
    1. choose from "choose from list windows"
    2. enter docEntry or itemCode or cardCode  and then press Find Button
    3. press "next/previous record button"
    4. press linked button (orange arrow)
    Choice 3 and 4 can be done by retrieve data from BusinessObjectInfo.objectKey (I've tested and it return entry key that is going to open correctly).
    but 1 and 2 can't (it return empty as I mention before).
    thanks
    Edited by: daron tancharoen on Aug 5, 2008 2:34 PM

  • Getting the length of a field in a database.

    I have a field in a database that has a char length of 20, is there anyway to get that length from the database.

    I probally didn't explain myself properley. The field might not have anything in it. The field would only except a length of 20, some have 10 others 5.
    I have a GUI repersenting a table in the database. When the user is inputting into this field I want to stop them from entering more than 20 Characters. I need to know how many characters the field will accept.
    I'm trying to stop my client from calling me up and saying that there something rong with the program because when he enters data, it only saves half of it.

  • How to get the length of apex_item in javascript?

    Hello all
    I am having a tabular report using apex_item, I want to know how can i get the length of the item in javascript? like we do in pl/sql using apex_application.g_f01.count().
    and one more thing, when I go to certain page, tab of that page is getting disabled, what should I do to make tab available always whether I am on that page or on any other page.
    Thanks
    Tauceef

    Hi Oli
    Thanks for replying, In my first question actually I am validating the report values in javascript for that I need the length of the apex_item to run the loop that many times.
    Like we can get the length using apex_application.g_f011.count in pl/sql process how to get the length in the javascript, is there a way for that?
    I got the answer for the second question, this is the one.
    Thanks
    Tauceef

  • How to get the length of a audio file without play it ?

    Now I know a method to get the length of a audio file by play it:
    1 Create a Player, and add a ControllerListener
    2.Start the Player
    3.In the ControllerListener's controllerUpdate method, use getMediaTime() by receiving a EndOfMediaEvent
    However I think this method is not convenience, if I don't want to play it how I can get the length of the audio file?
    Is anyone can help me?Really thanks a lot !

    I got the answer here:
    http://forum.java.sun.com/thread.jspa?threadID=5149132&tstart=15
    I tried getDuration() before, but it always return a same time, I think maybe I didn't realize the player.

Maybe you are looking for