Casting Hashtable to list

Hi
My evil teacher has given me an assignment that include casting a Hashtable to a list. I get no error when compiling,building or running the project, but when i try printing the list i get loads of errors. I am not a very experienced programmer so please keep the answer simple :D
public List getPerson(String aKey, String value){
List list = (List) contactList;
Iterator persons = list.iterator();
if(aKey == "name"){
while(persons.hasNext()){
Contact con = (Contact) persons.next();
if(con.getName().equals(value)){
list.add(con);
return list;
}

Take a look at the javadocs, and see if you can come up with a solution.
Maps contain key-value pairs (like a dictionary, you can look up a value if you have the key).
Now with that information, can you see any way to get a collection of keys, or values from a Map (Hashtable is an implementation of a map)
Hashtable Javadoc

Similar Messages

  • Properties, Casting, and Collections.list

    How do I make the following code work properly, without warnings?
    import java.util.Properties;
    import java.util.Collections;
    import java.util.Collection;
    class Test {
        public static void main(String [] argv){
            Properties p=new Properties();
            for (String s : Collections.list(p.propertyNames())){
                System.out.println(s);
    }I have tried casting the ArrayList result, and the passed in Enumeration.
    Christopher
    P.S. What does the first <T> mean in the declaration of Collections.list?
    public static <T> ArrayList<T> list(Enumeration<T> e)

    I'm pretty sure you can't. Let's gradually expand your code, filling in local variables so you can see why:
    for (String s : Collections.list(p.propertyNames()))becomes
    List<String> list = Collections.list(p.propertyNames()); // not typesafe
    for (String s : list)So why isn't that list typesafe? Well, let's keep going.
    Enumeration<String> enumeration = p.propertyNames(); // not typesafe
    List<String> list = Collections.list(enumeration);
    for (String s : list)The problem is that the method p.propertyNames() does not return an Enumeration<String>; it returns an Enumeration<?>. That's where your type safety problem shows up.
    You will notice that the Properties object extends Hashtable<Object,Object>. This means that it's entirely possible that the Properties object contains a non-String key.
    An ugly solution might be something like this:
    List<String> propertyNames = new ArrayList<String>();
    for (Object o : p.propertyNames()) propertyNames.add(o.toString());
    for (String s : propertyNames) ...Obviously, this won't work the same way if the Properties object contains a non-String key... but if you're willing to assume it doesn't, that solution should be fine.
    Cheers!

  • How to Cast Collection to List?

    Hi,
    I encounter a problem! When I cast a Collection instance to List, the
    JVM gave me a ClassCastException!
    Any suggestion?
    Thanks!

    Hi,
    that't because a Collection does not need to be an instance of List.
    public interface List extends Collection not vice versa!
    What do you want to do? Is it really necessary to have a List?
    If yes, you have to create a new instance:
    List answer = new ArrayList(formerCollection);Harri

  • Finding the min value in a hashtable

    Hi,
    I'm trying to work out the lowest value contained in a hashTable. So far I've got.
    import java.util.Enumeration;
    import java.util.Hashtable;
    import java.util.Vector;
    public class StoreValuesDouble extends Statistic {
          * Each object of the class (StoreValuesDouble) will have these attributes.
          * When you call the StoreValuesDouble class you can use
          * myDoubleValues (a Vector holding Double types),
          * Hashtable (a Hashtable using Double types as values and keys) and
          * nullValues (an Double currently set to 0.0).
         Vector<Double> myDoubleValues; //declare a variable myDoubleValues that is of data type Vector
         Hashtable<Double, Double> myValues; //declare a variable myvalues that is a data type Hashtable
         Double nullValues = 0.0; //Double attribute to count the number of null values contained in the vector
          * pass myDoubleValues to inValues
          * @param Vector /<Double/> a vector holding Double values
          * @param inValues the values in the vector
          * @return
         public void DoubleStat(Vector<Double> inValues) {
              myDoubleValues = inValues;
          * calculate the mean of myDoubleValues
          * @return mean of myDoubleValues as a double
         public double meanDouble() {
              double mean = 0;
              Double currentDouble;
              double nonNull = 0;
              for (double j = 0; j < myDoubleValues.size(); j++)
                   currentDouble = myDoubleValues.elementAt((int) j);
                   if (currentDouble != null) {
                        mean += currentDouble.doubleValue();
                        nonNull++;
              return mean / nonNull;
          * calculate the standard devitation of myDoubleValues
          * @return standard devitation of myDoubleValues as a double
         public double standardDeviationDouble() {
              double m = meanDouble();
              double t = 0.0;
              Double currentDouble;
              double n = 0;
              for (double j = 0; j < getDoubleValues(); j++) {
                   currentDouble = myDoubleValues.elementAt((int)j);
                   if (currentDouble != null) {
                        n = currentDouble.doubleValue();
                        t += (n - m) * (n - m);
              return Math.sqrt(t / (myDoubleValues.size() - 1.0));// n - 1 as sample varience
          * return the number of values of myDoubleValues to help calculate the mean & standard deviation
          * @return the size of myDoubleValues as a Double
         public double getDoubleValues() {
              return myDoubleValues.size();
          * compute the number of null values
          * @return a double value representing the number of null values
         public Double getDoubleNull() {
              Double nbNull = 0.0;
              // test if myIntValues is null
              if (myDoubleValues == null) {
                   System.out.println("Please enter values that are not null!");
                   return 0.0;
              // if not null, parse all values
                   // for each value, test if it is null or not
                   Double currentDouble;
                   for (double i = 0; i < myDoubleValues.size(); i++) {
                        currentDouble = myDoubleValues.elementAt((int)i);
                        if (currentDouble != null) {
                             /// nothing to do
                        else {
                             nbNull++;
              return nbNull;
    //find the MIN values in the Hashtable to give us the range (with the MAX value)
         public Double MinDouble()
              Double MinDouble = null;
              Double currentValue;
              for (double j = 0; j < myDoubleValues.size(); j++)
                   currentValue = myDoubleValues.elementAt((int) j);
                   if (currentValue != null){
                   if (currentValue <= MinDouble) {
                        MinDouble = currentValue;
              return MinDouble;
         /*find the MAX value in the Hashtable to give us the range (with the MIN value)
         public double MAX()
          * Create an instance of StoreValuesDouble to hold vector values and number of times the values
          * appear. StoreValuesDouble automatically contains the variables defined above
          * (myDoubleValues, myValues and nullValues) we have to initialise myDoubleValues and myValues
          * as they have been defined but not initialised. nullValues has been defined (int) and initialised (0).
          * @param Vector /<Double/> a vector holding Double values
          * @param inValues the values in the vector
          * @return
         public StoreValuesDouble(Vector<Double> inValues) {
              myDoubleValues = inValues; //the attribute myDoubleValues defined in the StoreValuesDouble class
              //is the inValues parameter, this allows us to store the Vector in inValues
              myValues = new Hashtable<Double, Double>(); // create an instance of/initialise Hashtable
          * Now define the methods to make the instance StoreValuesDouble do what we want it to do
          * (ie parse all the double values of the myDoubleValues Vector attribute.
         public void computeDoubleValues() {
              Double currentDouble;//local variable to store the current read Double object
               * Use a for loop to read through all the values contained in the vector
              for (double i = 0; i < myDoubleValues.size(); i++) {
                   currentDouble = myDoubleValues.elementAt((int)i);
                   //currentDouble is now the Double object stored at i
                   //to check that i is not null we use the if statment
                   if (currentDouble != null) {
                        //i is not null so we want to add it to the hashtable. Rather than writing a lot of code
                        //here to do checking and adding we just call a method that can be written seperately
                        updateDoubleTable(currentDouble);
                   else {
                        //i is null so we just count it by adding it to our nullValues attribute
                        nullValues++;
          * Update the current distribution of Doubles
          * @param Double for the value of the key
          * @param inDouble for the value entered into the Hashtable (the object)
         public void updateDoubleTable(Double inDouble) {
              //First test that variable inDouble is not null
              if (inDouble != null) {
                   //update the table myValues this involves two tasks
                   //1)see if the double object has already been seen
                   //so we create a local variable to test the Hashtable
                   boolean alreadyPresent;
                   alreadyPresent = myValues.containsKey(inDouble);
                   //here we check whether inDouble is already in myValues
                   if (alreadyPresent) {
                        //if it is present we need to increase the counter
                        Double counter = myValues.get(inDouble);
                        //local variable counter to get the value associated to the key inDouble
                        Double newCounter = new Double(counter.intValue() + 1.0);
                        //update counter values and then ...
                        myValues.put(inDouble, newCounter);
                        //put into myValues
                        //as Hashtable can store only Objects, we cannot use primitive types
                        // so we use Objects related to primitive types as Integer, Float, Double
                        // or Boolean (here, we use Double)
                   } else {
                        //store the double and set it's counter to 1
                        myValues.put(inDouble, new Double(1));
              } else {
                   //do nothing
         //now we want to display the values
         public void displayDoubleTable() {
              // to display the distribution, we need to parse all the keys of the
              // hashtable and access to the value associated to each key
              Enumeration<Double> keys = myValues.keys();
              Double currentKey;
              Double currentValue;
              System.out.println("");
              System.out.println("Hashtable Information:");
              System.out.println("");
              System.out.println(myDoubleValues.size() + " Double objects in initial vector");
              System.out.println("");
              while (keys.hasMoreElements()) {
                   currentKey = keys.nextElement();
                   currentValue = myValues.get(currentKey);
                   System.out.println("The value " + currentKey.doubleValue()
                             + " has been seen " + currentValue.doubleValue()
                             + " time(s) in the initial Vector");
              System.out.println("");
              System.out.println("There were " + nullValues
                        + " null Double object(s) in the inital Vector");
         }As part of the StoreValuesDouble class. And to display it.
    package statistics;
    import java.util.Vector;
    public class TestStatDouble {
         static Vector<Double> doubleVector;
          * Create and initialise a vector of values and compute the mean,
          * standard deviation, distribution and MIN/MAX values.
         public static void main(String[] args) {
               // initialise the values in initValues
              initValues();
              // create an instance of StoreValuesDouble taking double as the parameter
              StoreValuesDouble is = new StoreValuesDouble(doubleVector);
              //Display the results
              displayVectorContent(doubleVector);
              System.out.println("");
              System.out.println("Number of null values: " + is.getDoubleNull());
              System.out.println("Number of non-null values is: " +(is.getDoubleValues() - is.getDoubleNull()));
              System.out.println("Number of all values: " + is.getDoubleValues());
              System.out.println("The mean is: " + is.meanDouble());
              System.out.println("Standard deviation is: " + is.standardDeviationDouble());
              System.out.println("The lowest value is " + is.MinDouble());
              System.out.println("");
               * now I want to display the results from the displayTable method in the StoreValuesDouble
               * class so I create an instance of StoreValuesDouble and use the computeDoubleValues and
               * displayDoubleTable methods.
              StoreValuesDouble storeValues = new StoreValuesDouble(doubleVector);
              storeValues.computeDoubleValues();
              storeValues.displayDoubleTable();
          * create the class method initValues() to add values to the Vector doubleVector
         public static void initValues()
              doubleVector = new Vector<Double>();
              doubleVector.addElement(null);
              doubleVector.addElement(new Double(10.9));
              doubleVector.addElement(new Double(15.95));
              doubleVector.addElement(new Double(17));
              doubleVector.addElement(null);
              doubleVector.addElement(new Double(1));
              doubleVector.addElement(new Double(4));
              doubleVector.addElement(new Double(10.499));
              doubleVector.addElement(null);
              doubleVector.addElement(new Double(10.4999));
              doubleVector.addElement(new Double(17));
              doubleVector.addElement(new Double(-15));
              doubleVector.addElement(null);
              doubleVector.addElement(new Double(14));
              doubleVector.addElement(new Double(20));
              doubleVector.addElement(new Double(-3));
              doubleVector.addElement(null);
              doubleVector.addElement(new Double(9));
              doubleVector.addElement(new Double(1.5));
              doubleVector.addElement(null);
              doubleVector.addElement(new Double(10.22));
              doubleVector.addElement(new Double(15.23));
              doubleVector.addElement(new Double(17.91));
              doubleVector.addElement(null);
          * class method to print values contained in the vector doubleVector to the console.
          * @param doubleVector the Vector to be displayed
         public static void displayVectorContent(Vector doubleVector)
              Double currentDouble;
              System.out.println("Double values within the Vector:");
              for (int i=0; i<doubleVector.size();i++)
                   try
                        currentDouble = (Double) doubleVector.elementAt(i);
                        if (currentDouble != null)
                             System.out.print(currentDouble.toString() + " ");
                   catch(ClassCastException cce)
                        System.out.print(cce.getMessage() + " ");
                        cce.printStackTrace();
              System.out.println("");
         It compiles fine but when I try and run it I get a
    Exception in thread "main" java.lang.NullPointerException
         at statistics.StoreValuesDouble.MinDouble(StoreValuesDouble.java:139)
         at statistics.TestStatDouble.main(TestStatDouble.java:37)
    TestStatDouble 37 is
    System.out.println("The lowest value is " + is.MinDouble());139 is
    if (currentValue <= MinDouble) {I guess the problem's in my if loop but I'm not sure why. Any help would be appreciated.
    Message was edited by:
    Ali_D

    Couple of points about your code:
    1. Don't declare your instance variables as solid types, declare them using their interfaces (where applicable), so in your case don't specifiy that you are using Vector or Hashtable, use List and Map. This will allow you to easily change your code to use a different collection, if and when appropriate. Also the unnecessary overhead of Vectors synchronisation means that you should use ArrayList instead of vector (that means that you will have to use get(int) instead of elementAt() but that's a very small price to pay.
    2. Declare local variables as close to their point of usage as possible. (Unless you need to do this for your course work, in which case you don't have a choice).
    3. Use the appropriate data type. For your count of null values you should be using an int or a long (you can't have a fractional count value!) Also, this should have been obvious to you, when you had to cast the value to an int for use with your lists. (Using double as an index is a very bad idea... And before you go posting the question, do a search on why floating point precision may not give you the results you expect)
    4. Code defencively... e.g. in your meanDouble() method, you set nonNull to 0, and then you do a division using that value. What do you think is going to happen if your loop doesn't execute once? Division by zero... You should handle these cases, rather than letting them fail ignominiously.
    5. If you are doing code like this...    if (currentDouble != null) {
            // / nothing to do
        } else {
            nbNull++;
        } Why have the empty block? You should just do the inverse.
        if (currentDouble == null) {
            nbNull++;
        } Far simpler, and expresses exactly what you are trying to do, not what you are not trying to do.
    6. Enumeration --- What version of java is that course being run in? I can see that you are using autoboxing, so it has to be 1.5 so, WHY is your lecturer encouraging the use of Vectors, Hashtables, and Enumerations!?!?!
    Anyway, that should be enough to be going on with.

  • Converting a hashtable to an array (CORBA sequence)

    Hi all,
    I wish to convert the contents of a hashtable to an array (well a CORBA sequence), but I am having a bit of trouble.
    I have a CORBA struct called 'Equipment', and an unbounded sequence of Equipment structs called 'EquipmentList':
              struct Equipment {
                   string name;
                   string description;
              typedef sequence<Equipment> EquipmentList;I have a Java hashtable called equipmentList which contains a list of equipment with key 'name' and corresponding value of 'description'.
    The following code is trying to convert from the hashtable to the CORBA sequence:
              Equipment equipList[] = new Equipment[equipmentList.size()]; // make sequence same size as hashtable.
              for (int i = 0; i < equipmentList.size(); i++) {
                   equipList[i] = new Equipment(); // make element a valid 'Equipment' object.
                   equipList.name = equipmentList.name; // give each sequence element value 'name' the value of the hashtable key value 'name'
                   equipList[i].description = equipmentList.description; // same with 'description' value
    I know the conversion is completely wrong, and it obviously brings up 2 errors a compile time:HireCompanyServer.java:81: cannot find symbol
    symbol : variable name
    location: class java.util.Hashtable
    equipList[i].name = equipmentList.name;
    ^
    HireCompanyServer.java:82: incompatible types
    found : java.lang.Object
    required: java.lang.String
    equipList[i].description = equipmentList.get(equipList[i
    ].name);
    ^
    Note: Some input files use unchecked or unsafe operations.
    Note: Recompile with -Xlint:unchecked for details.
    2 errors
    I know this might be a long-winded question, but I am having real difficulty fixing this, and would kindly appreciate some more advanced programmers to give me any hints or fixes for my code.
    Thanks                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    JonBetts2004 wrote:
    I know this might be a long-winded question, but I am having real difficulty fixing this, and would kindly appreciate some more advanced programmers to give me any hints or fixes for my code.Not quite sure how 'struct' got in there, but unless you're using generics to set up your HashTable, you have to cast anything you get from your list to the correct type. Have a look at the HashTable method list and I think you'll work out what you want.

  • 2 levels array/list

    i want to create 2 levels array/list.
    Structure:
    0 => `array`("id" => 10, "name" => "john")
    1 => `array`("id" => 11, "name" => "peter")
    2 => `array`("id" => 12, "name" => "michael")
    for `array's` i use Hashtable's, and them i put into an ArrayList.
    But ArrayList get(int index) returns an Object, not a Hashtable.
    And my question is, how to make a Hashtable from this returned Object?
    Thanks...

    Simply by casting:
    Hashtable table = (Hashtable)yourArrayList.get(index);
    If you meant that ... otherwise correct me.

  • Converting  String  to  List

    I want to convet the String to a List. But I get an error can not cast String to List.
    Help???
    String str = "Y";
    List myList = (List) str;Thanks.

    1. Have your String initialized
    2. Have your list object
    3. Add your string in to the list (LinkedList in this
    eg's case)... Easy Pizy!
    String str = "a";
    LinkedList myList = new LinkedList();
    myList.add(str);
    So if you want to pass 'str' as a list. Just
    use myList. (myList is a list verion of String
    'str').
    Well, this doesn't change your String into a List, but it creates a List and inserts the String as the first entry there. BIG difference!
    Maybe you tell us what you are trying to do, and we tell you how to achieve it.

  • DropDownList casting problem

    Table
    int id
    string name
    Tables extends table
    Array<TableLinks> of children
    TableLinks
    Table rightTable
    In flex, I get a list of Tables from my web service
    Display a combobox with the list of Tables
    Once someone selects from the list the list of TableLinks is populated in a datagrid
    in the rightTable column it displays the rightTable.name in the label
    When you edit the column a dropdownlist shows
    <mx:DataGridColumn id="tableNameDC"
       headerText="Table"
       editable="true"
       dataField="rightTable"
       labelFunction="tableFormat"
       editorDataField="value"
       width="150">
    Is there anyway to cast my Tables list to type Table here?
    Currently, I keep the list as Tables
    When you select and item the value is saved to a value object but casted from Tables to Table
    When you exit the dropdownlist the get value function returns the Table value Object.  But for some reason, it keeps telling me its null.
    Its as if when I cast the Tables item to Table it fails.
    public function get value():TableDto
    return rightTableDto
    protected function selectableDropDown_closeHandler(event:DropDownEvent):void
    rightTableDto = selectableDropDown.selectedItem as TableDto;
    So, if the first question is not doable,  what do you think I am doing wrong?

    Hi,
       You can use onClientSelect to trigger the javascript code.
    Here is a sample code to trigger the javascript
    <%String projectId="";%>
    <hbj:dropdownListBox
         id="projectIdDL"
         width="110"
         onClientSelect="getStages()">
    <%projectId=myContext.getParamIdForComponent(projectIdDL);%>
         </hbj:dropdownListBox>
    <script>
    var proid=document.getElementById('<%=projectId%>');
    function getStages()
    //code
    </script>
    Hope this will oslve your problem to trigger a javascript code when you select a value in DropdownListbox
    Regards
    Padmaja

  • Hashing with double linked list....

    Okay, everything compiles great but I'm getting a NullPointerException upon running the program.
    'line' is a string from a file to let you know that much. 'firstnode', 'nownode', and 'lastnode' are pointers in my array linked list 'anArray'. I know clever names. lol But hey, my professor uses variable names like 'X' 'T' and 'G' all the time, confusing bastard. :-) Anywho... I put a note in the code so you can see where this exception is taking place. Any help is 100% welcomed and appreciated!
         while( line != null )
         int hashindex = hash(line, 20);
         if(firstnode[hashindex] == null)
                 firstnode[hashindex] = nownode[hashindex] = lastnode[hashindex] = new ListNode( line );
         else
                 nownode[hashindex] = new ListNode( line );
    //This line is the exception, if I comment it out, the next line throws it
              anArray[hashindex].CONS(nownode[hashindex], lastnode[hashindex]);
              anArray[hashindex].LCONS(lastnode[hashindex], nownode[hashindex]);
    //If I comment out the 2 lines above this line DOES NOT throw an exception, weird
              lastnode[hashindex] = nownode[hashindex];
         line = input.readLine();
         }

    Okay, here's some more code... Just the top portion of the program. Keep in mind that methods like CONS, LCONS, CDR, and LCDR are just using the ListNode methods such as .ptr and stuff... My professor makes us use this ADT he provided. I can post ALL code if you would like but I dont think all that is necessary.
    static BufferedReader input, console;
    static List hashtable = new List();
    static List[] anArray = new List[20];
    static ListNode[] nownode, firstnode, lastnode;
    static String message = "";
    static int nodecount = 0;
    public static void openFile()
    //Opens the file for input and throws and exception if the file is not there
         File taskFile = new File("prices.txt");
         try
             input = new BufferedReader(new FileReader( taskFile ));
         catch( FileNotFoundException fileNotFoundException )
         outputStuff("Error", "The file does not exist!", "error");
    public synchronized static void setupTable() throws IOException
         firstnode = new ListNode[20];
         nownode = new ListNode[20];
         lastnode = new ListNode[20];
         String line = input.readLine();
         firstnode[0] = nownode[0] = lastnode[0] = new ListNode( line );
         while( line != null )
         hashindex = hash(line, 20);
         if(firstnode[hashindex] == null)
                 firstnode[hashindex] = nownode[hashindex] = lastnode[hashindex] = new ListNode( line );
         else
                 nownode[hashindex] = new ListNode( line );
              anArray[hashindex].CONS(nownode[hashindex], lastnode[hashindex]);
              anArray[hashindex].LCONS(lastnode[hashindex], nownode[hashindex]);
              lastnode[hashindex] = nownode[hashindex];
         line = input.readLine();
         for(int i = 0; i <= 20; i++)
              while( nownode[i] != null)
              message += "String = " + anArray.info( nownode[i], 0 ) + "\tIndex = " + i + "\n";
         nownode[i] = anArray[i].CDR(nownode[i]);
         outputStuff("test", message, "blah");
    }//End setupTable

  • Problem create List E []

    Hello. Got problems when I try to create one "Array" filled with "List" as type. Tried:
    List<E>[] name = List<E>[size]; (Compilation problem)
    and
    List<E>[] name = (List<E>[])(new Object[size]) (cannot cast object to list)Got any suggestions?

    Hunter78 wrote:
    Thanks. It seems to compile but now I recive "NullPointerException" when I try to add anything into the list. Any idea why?
    Example:
    public void method(E e){
    List<E>[] name = (List<E>[])new List[size];
    List list = name[0];
    list.add(e);     (NullPointerException)
    }edit: using array becouse it�s most naturale when the size is known.Umm... have you ever used arrays of references before? "name" is an array of references, because List is a reference type (everything that is not a primitive type is a reference type). So when you create the array, it is initialized with null references (the default value for references). i.e. the references don't point to any object. So you have no List object to add anything to. It's the same reason why this won't work:
    List foo = null;
    foo.add(e);

  • Casting a collection or an array

    Hi, let's say I have a Class A and a Class B that extends A.
    Ok, first question, I have : A[] anArrayOfA but I know that all those are in fact instances of B. Is there a proper way to get a B[] from it ?
    Same question, but this time let's say I have a List<A> aListOfA instead of the array.
    Thanks.
    Message was edited by:
    JF_L

    I tried the cast, it provokes an compiler
    error, not a warning.Err, sure, I don't know what I was thinking :)
    Could you provide some more code here? If B extends A and you want to return a List of A, you might be able to weaken the return type definition. A List<A> of course is not the same as or castable to a List<B>, whether or A is a B or vice versa. You can always go by casting to raw List (which will give the warning I mentioned) but that would be bad practice anyway.
    If you really need a List<A> but have List<B> and B extends A, you could create a new list from List<B>, e.g. new ArrayList<A>(myListB). Of course, this does not work the other way around, as a List<B> does not take A elements.
    Copying lists or arrays always does cost. If you need massive copying in your code, you should rethink the design of your implementation. If you need more specific types in your parts of the implementation, where you get only less specific ones, you may be better of with using casts and instanceof checks.

  • JTable + Hashtable + Collection doesn't seem to work properly

    Hi folks,
    I'm having a problem with JTree class. Basically, I want to instantiate it by using an Hashtable, though
    depending on the fact that I use collection or arrays the result can substantially vary.
    Take the following use case:
    import javax.swing.*;
    import java.util.*;
    public class Tree extends JApplet{
      public Tree(){
        super();
        setSize(300, 250);
        init();
        setVisible(true);
      public void init(){
        Hashtable<String,List<String>> hash = new Hashtable<String,List<String>>();
        hash.put("Foo", Arrays.asList("Bar"));
        JTree tree = new JTree(hash);
        getContentPane().add(tree);
    }This displays a wrong tree, in fact you should have a Foo node that contains a Bar leaf.
    Now if I use array instead of collections (generics are not the problem) everything work just as
    expected!?
    import javax.swing.*;
    import java.util.*;
    public class Tree extends JApplet{
      public Tree(){
        super();
        setSize(300, 250);
        init();
        setVisible(true);
      public void init(){
        Hashtable<String,String [] > hash = new Hashtable<String,String []>();
        hash.put("Foo", new String []{"Bar"});
        JTree tree = new JTree(hash);
        getContentPane().add(tree);
    }Considering that the constructor of JTree allows the following instantiation for Hastable:
    public JTree(Hashtable<?,?> value)the use of wildcards let me assume that I can put whatever I like as the type of my keys/values.
    Am I missing something or this is indeed some very strange (buggy) behavior.
    Cheers,
    Mirco

    lins314159 wrote:
    [Javadocs for createChildren method|http://java.sun.com/javase/6/docs/api/javax/swing/JTree.DynamicUtilTreeNode.html#createChildren%28javax.swing.tree.DefaultMutableTreeNode,%20java.lang.Object%29]
    If you look in the source code for JTree, there's no mention of Lists in there. Not quite sure why they handle Vectors and Hashtables only instead of Lists and Maps.Hi lins,
    thanks for taking the time for giving me your though.
    I have take a glance at the javadoc for method createChildren, but once again it tells me that if I have an entry of the type
    <A,Collection<B>> I should get a Node named after the object of type A and whose leaf are the ones contained in the collection.
    I agree with you that is bizarre that the JTree constructor only accept Hashtable (and not Map, that appear to me more convenient);
    but I can live with that as long as the value field of the hashtable behave as I would expect.
    I'm not an experienced Java programmer, so if any of you gurus has any thoughts on that, please let me know.
    Cheers,
    Mirco
    Edited by: Mirco on Feb 29, 2008 12:07 AM

  • Pod Casts - auto downloading not working

    On a WIN7 PC, running ITunes v12.0.1.26 I subscribe to multiple Pod Casts.
    All are marked to
    Subscribe = ON
    Limit Episodes = NO
    Download Episodes = ON
    Delete Played Episodes = ON
    Only the first pod cast in the list is following these rules.
    The other pod casts do not auto download.
    If I hit the REFRESH button, it shows that the last update was in 12/2014, when I manually downloaded the latest updates for that pod cast.
    Any ideas?

    I finally solved this by changing the Auto-Lock settings. Mine were set to Auto Lock in 2 minutes. I changed the setting to 15 minutes and my New Yorker Magazine downloaded without incident -- although it took much more than 15 minutes. (I now suspect that my prior setting was the reason my Newsstand publications never downloaded automatically.) I have now reset Auto-Lock to "Never" to test whether that works in the future for automatic downloads --basically because my DSL speed is not optimum.

  • Flash Builder 4.5 Doesn't Know How To Cast?!

    I just upgraded from FB 3 and I am starting to feel very disappointed. Fonts look horrible (antialising-wise) and code which worked perfectly now acts weird. Case in question:
    Dirt simple: I got a class called G3Widget with a property named Text.
    trace(G3Widget(sender).Text);
    This code COMPILES and RUNS successfully. HOWEVER:
    1. I get a warning on it: Access of undefined property Text
    2. I get no code assist: when I hit the . (dot) after the (sender) I get no code assist with properties of the Widget Class.
    What's wrong? I can't believe that FB 4.5 doesn't do what FB3 did.

    Oh, and I forgot to mention that I get the same stupid error for this code which worked perfectly in FB3:
    for (var key: Object in Event_MouseDown_Callbacks) (key as Function)(sender == null ? this : sender, flashEvent, Event_MouseDown_Callbacks[key]);
    I get the error for (key as Function). This code is within a Function of mine.
    As for my original post, I just re-tested that issue in FB3 and there, when I hit . (dot) after the cast, it CORRECTLY LISTS all the members of the G3Widget Class.
    I've looked in the options of Flash Builder 4.5 for an hour trying to see why it behaves like it does. No luck. And it's probably not an option. It's just that, by default, it doesn't list the members of the type after you cast it, which, in my opinion, is a HORRIBLE mistake. I'm going back to FB 3.

  • Relinking existing video-cast to iTunes

    This seemed a simple drag and drop solution but unfortunately doesn't work the way I would like to. I have 15+ Video-casts which are directly imported into iTunes via the website which produces them. Ever since the site has offered an iTunes video-cast subscribe which lists all the entries. (dimmed to be retrieved - highlighted once downloaded)
    How can I tell iTunes that some of the dimmed files are already downloaded and located in the itunes library? If I drag and drop the files it just creates a separate entry in my podcast listing, instead of "highlighting" the title of the specific video-cast in the subscription (feed) list. (Same for "add to library" action)
    Does this makes sense?
    Note: searched Doug's scripts & iLounge but no luck yet!

    hmmmm. what version of QuickTime are you running, m1ndy?
    there were issues with QT 7.0.4, where if a podcast file on a server was malformed in precisely the right way it could crash itunes with that "itunes has encountered an error" message while downloading.
    if you've got a 7.0.4, try upgrading to 7.1:
    Quicktime 7.1 Standalone Installer
    (if you're getting the 7.0.4 podcast crash, the podcasts might not play tremendously well, because they are malformed. but they shouldn't crash your itunes.)

Maybe you are looking for

  • Setting changes with 2.0 Update??

    Has anyone noticed you cannot set the time anymore before the phone goes in idle?It used to be on the same screen when you adjust the brightness...but it isn't there anymore. I have searched everywhere else but can't find it. Anybody else know if you

  • SWF in pdf  format issue

    Hi, I have exported the swf file in pdf and ppt format. I have made all the setting in web server level, which are found in forums. the crossdomain.xml and the adobe global security panel settings. when I open in my system there is no any pop up wind

  • How to create a toggle button which has some id associated with it

    Hi all, This is my problem <formid><some value in a text box><toggle button> here formid is a hidden parameter. There can be multiple records of this type...the user can change the text box as well as toggle any record. Now im unable to create a togg

  • How to uninstall the command line tools?

    I installed the command line tools in Xcode 4.5 from the preferences : downloads : command line tools. If i want to uninstall this component, what should I do? PS: I saw an answer in the Apple Support Communities about how to uninstall the Xcode 4.3

  • There seems to be a problem with the file download. For troubleshooting tips, please visit our customer support page

    There seems to be a problem with the file download. For troubleshooting tips, please visit our customer support page.