Probably tons of mistakes, sorry. I'm new to java and I'm having a rather hard time with all the syntax and whatnot. I can't get past this error but I fail to see where it is. I can't even compile because I get the message: "...uses unchecked or unsafe operations. Note: Recompile with -Xlint: unchecked for details" Help, please.  This is supposed to implement the Queue interface which is pretty much just  public boolean enqueue(Item item); public Item dequeue(); public int size; public boolean isEmpty(); public boolean isFull();   I did try to make it circular but I don't know if I've succeeded.  I think it's those generics that bring about the problem, i don't know.       public class ArrayQueue&lt;Item&gt; implements Queue&lt;Item&gt; {     private Item[] q;     public int N = 0;     private int tail = 0;     private int head = 0;      public ArrayQueue(int capacity) {     q = (Item[]) new Object [capacity];     }      public boolean enqueue(Item item) {         if (isFull())             return false;         q[tail++] = item;          if(tail == q.length )             tail = 0;         N++;         return true;     }      public Item dequeue( ) {         if (isEmpty( ) )             return null;         N--;         Item headItem = q[head];         q[head++] = null;         if(head == q.length )             head = 0;          return headItem;     }        public int size( ) {         return N;     }      public boolean isFull() {         return N == q.length;     }       public boolean isEmpty() {         return N == 0;     } }
3732
For example:  javac Foo.java Note: Foo.java uses unchecked or unsafe operations. Note: Recompile with -Xlint:unchecked for details.
33911
I have been reading through the  and was curious about the  declaration. I personally have never used it, however I am interested in exploring the language.   What is a good example of using friend?    Reading the FAQ a bit longer I like the idea of the &lt;&lt; &gt;&gt; operator overloading and adding as a friend of those classes. However I am not sure how this doesn't break encapsulation. When can these exceptions stay within the strictness that is OOP?
40567
I'm working on a project where i find i'm checking for the following in many, many places:  if(item.Rate == 0 || item.Rate == null) { }   more as a curiousity than anything, what's the best way to check for both cases?  I've added a helper method which is:  public static bool nz(object obj) {     var parsedInt = 0;     var parsed = int.TryParse(obj.ToString(), out parsedInt);     return IsNull(obj) || (parsed &amp;&amp; parsedInt == 0); }   Is there a better way?
1843
I have a couple of questions about generic wildcards in Java:   What is the difference between List&lt;? extends T&gt; and List&lt;? super T&gt;? What is a bounded wildcard and what is an unbounded wildcard?
9792
Yesterday I had a two-hour technical phone interview (which I passed, woohoo!), but I completely muffed up the following question regarding dynamic binding in Java.  And it's doubly puzzling because I used to teach this concept to undergraduates when I was a TA a few years ago, so the prospect that I gave them misinformation is a little disturbing...  Here's the problem I was given:  /* What is the output of the following program? */  public class Test {    public boolean equals( Test other ) {     System.out.println( "Inside of Test.equals" );     return false;   }    public static void main( String [] args ) {     Object t1 = new Test();     Object t2 = new Test();     Test t3 = new Test();     Object o1 = new Object();      int count = 0;     System.out.println( count++ );// prints 0     t1.equals( t2 ) ;     System.out.println( count++ );// prints 1     t1.equals( t3 );     System.out.println( count++ );// prints 2     t3.equals( o1 );     System.out.println( count++ );// prints 3     t3.equals(t3);     System.out.println( count++ );// prints 4     t3.equals(t2);   } }   I asserted that the output should have been two separate print statements from within the overridden equals() method: at t1.equals(t3) and t3.equals(t3).  The latter case is obvious enough, and with the former case, even though t1 has a reference of type Object, it is instantiated as type Test, so dynamic binding should call the overridden form of the method.  Apparently not.  My interviewer encouraged me to run the program myself, and lo and behold, there was only a single output from the overridden method: at the line t3.equals(t3).  My question then is, why?  As I mentioned already, even though t1 is a reference of type Object (so static binding would invoke Object's equals() method), dynamic binding should take care of invoking the most specific version of the method based on the instantiated type of the reference.  What am I missing?
23909
Looking for reviewers to suggest optimization and improvements, and to evaluate coding practices.  final class Variables {     private final int x;     private final int y;      Variables(int x2, int y2) {         this.x = x2;         this.y = y2;     }      public int getX() {         return x;     }      public int getY() {         return y;     }      @Override public String toString()  {          return "x = " + x + " y = " + y;     } }  public final class FindMissing {      private FindMissing() {};      /**  * Takes an input a sorted array with two variables that repeat in the  * range. Remaining variable are consecutive. and returns two variables that repeats  *   * eg: for a range of 1,2,3,4, a valid input is [1, 4], [1, 3] etc.  *   * @param a : the sorted array.  */ /*  * Why is start needed ?  * If start is not given then if a1 is empty how do we know if missing numbers were  * [1, 2] or [4, 5] ??.   */ public static Variables sortedConsecutiveTwoMissing (int[] a, int startOfRange) {     if (a == null) throw new NullPointerException("a1 cannot be null. ");      int low = startOfRange;     // calculating the highest value of the range. it needs to be 2 more than length since all elememts are consecutive.     int high = startOfRange + (a.length - 1) + 2;      int i = 0;     boolean foundX = false;     int x = 0;       while (i &lt; a.length) {         if (a[i] != low) {             if (foundX) {                 return new Variables(x, low);             } else {                 x = low;                 foundX = true;             }         } else {             i++;         }         low++;     }      return new Variables(x, high);  }  public static void main(String[] args) {         // unsortedConsecutiveTwoMissing         int[] a6 = {1, 4};         System.out.println("Expected 2 and 3, Actual " + sortedConsecutiveTwoMissing(a6, 1));         // unsortedConsecutiveTwoMissing         int[] a7 = {-4, -1};         System.out.println("Expected -3 and -2, Actual " + sortedConsecutiveTwoMissing(a7, -4));         int[] a8 = {-4, -3, -2, -1};         System.out.println("Expected 0 and 1, Actual " + sortedConsecutiveTwoMissing(a8, -4));         int[] a9 = {5};         System.out.println("Expected 4 and 6, Actual " + sortedConsecutiveTwoMissing(a9, 4));         }      }
3385
In the two following snippets, is the first one safe or must you do the second one?  By safe I mean is each thread guaranteed to call the method on the Foo from the same loop iteration in which the thread was created?  Or must you copy the reference to a new variable "local" to each iteration of the loop?  var threads = new List&lt;Thread&gt;(); foreach (Foo f in ListOfFoo) {           Thread thread = new Thread(() =&gt; f.DoSomething());     threads.Add(thread);     thread.Start(); }   -  var threads = new List&lt;Thread&gt;(); foreach (Foo f in ListOfFoo) {           Foo f2 = f;     Thread thread = new Thread(() =&gt; f2.DoSomething());     threads.Add(thread);     thread.Start(); }   Update: As pointed out in Jon Skeet's answer, this doesn't have anything specifically to do with threading.
59558
I am looking at some code and it has this statement:    ~ConnectionManager() {     Dispose(false); }   The class implements the IDisposable interface, but I do not know if that is part of that the tilde(~) is used for.
16158
Consider this example (typical in OOP books):    I have an Animal class, where each Animal can have many friends. And subclasses like Dog, Duck, Mouse etc which add specific behavior like bark(), quack() etc.  Here's the Animal class:  public class Animal {     private Map&lt;String,Animal&gt; friends = new HashMap&lt;&gt;();      public void addFriend(String name, Animal animal){         friends.put(name,animal);     }      public Animal callFriend(String name){         return friends.get(name);     } }   And here's some code snippet with lots of typecasting:  Mouse jerry = new Mouse(); jerry.addFriend("spike", new Dog()); jerry.addFriend("quacker", new Duck());  ((Dog) jerry.callFriend("spike")).bark(); ((Duck) jerry.callFriend("quacker")).quack();   Is there any way I can use generics for the return type to get rid of the typecasting, so that I can say      jerry.callFriend("spike").bark(); jerry.callFriend("quacker").quack();   Here's some initial code with return type conveyed to the method as a parameter that's never used.   public&lt;T extends Animal&gt; T callFriend(String name, T unusedTypeObj){     return (T)friends.get(name);         }   Is there a way to figure out the return type at runtime without the extra parameter using instanceof? Or at least by passing a class of the type instead of a dummy instance. I understand generics are for compile time type-checking, but is there a workaround for this?
19919
I ran into an interesting behavior recently.  It seems that if I override .equals() to take a parameter other than Object, it doesn't get called.  Can anyone explain to me why this is happening?  It seems to violate my understanding of polymorphism in OOP, but maybe I'm missing something.  Here's much simpler code that shows what I'm seeing:  public class MyClass {   private int x;   public MyClass(int n) { x = n; }   public boolean equals(Object o) { return false; }   public boolean equals(MyClass mc) { return x == mc.x; }   public static void main(String[] args) {     List&lt;MyClass&gt; list = new ArrayList&lt;MyClass&gt;();     list.add(new MyClass(3));     System.out.println("Contains 3? " + list.contains(new MyClass(3)));   } }   When this is run, it prints "Contains 3? false".  It looks like the equals(Object) function is called, even though there is another that would work.  By contrast, if I write equals like this the code works as expected:  public boolean equals(Object o) {   if(!(o instanceof MyClass))     return false;   MyClass mc = (MyClass)o;   return x == mc.x; }   Why isn't it figuring out which version of the function to call based on the type of the parameter?
6108
Why do I get compiler errors with this Java code?  1  public List&lt;? extends Foo&gt; getFoos() 2  { 3    List&lt;? extends Foo&gt; foos = new ArrayList&lt;? extends Foo&gt;(); 4    foos.add(new SubFoo()); 5    return foos; 6  }  Where 'SubFoo' is a concrete class that implements Foo, and Foo is an interface.  Errors I get with this code:   On Line 3: "Cannot instantiate ArrayList&lt;? extends Foo&gt;" On Line 4: "The method add(capture#1-of ? extends Foo) in the type List&lt;capture#1-of ? extends Foo&gt; is not applicable for the arguments (SubFoo)"   Update: Thanks to Jeff C, I can change Line 3 to say "new ArrayList&lt;Foo&gt;();".  But I'm still having the issue with Line 4.
86715
I'm looking at some GXT code for GWT and I ran across this use of Generics that I can't find another example of in the Java tutorials. The class name is  if you want to look at all of the code.  Here are the important parts:  private RpcMap map;  public &lt;X&gt; X get(String property) {   if (allowNestedValues &amp;&amp; NestedModelUtil.isNestedProperty(property)) {     return (X)NestedModelUtil.getNestedValue(this, property);   }   return map == null ? null : (X) map.get(property); }   X is defined nowhere else in the class or anywhere in the hierarchy, and when I hit "go to declaration" in eclipse it just goes to the &lt;X&gt; in the public method signature.  I've tried to call this method with the following two examples to see what happens:  public Date getExpiredate() {     return  get("expiredate"); }  public String getSubject() {     return  get("subject"); }   They compile and show no errors or warnings.  I would think at the very least I would have to do a cast to get this to work.  Does this mean that Generics allow a magic return value that can be anything and will just blow up at runtime?  This seems counter to what generics are supposed to do.  Can anyone explain this to me and possibly give me a link to some documentation that explains this a little better?  I've went through Sun's 23 page pdf on generics and every example of a return value is defined either at the class level or is in one of the parameters passed in.
282
Conditions: do not modify the original lists; JDK only, no external libraries. Bonus points for a one-liner or a JDK 1.3 version. Is there a simpler way than: List&lt;String&gt; newList = new ArrayList&lt;String&gt;(); newList.addAll(listOne); newList.addAll(listTwo);
7798
According to the , 3rd edition:        I wish to understand why this decision has been made. What's wrong with generic exceptions?  (As far as I know, generics are simply compile-time syntactic sugar, and they will be translated to Object anyway in the .class files, so effectively declaring a generic class is as if everything in it was an Object. Please correct me if I'm wrong.)
96022
I had the following exception thrown at me when trying to process more than one selected records via a custom button in the list view.    Class Code  global class MerchandiseInventoryClass {      webservice static void ConverttoInventory(String[] merchandise_id)    {        //Convert Merchandise collection into Inventory Collection...         Merchandise__c[] merchandise_collection = [SELECT ID,Author__c,Book_Title__c,Edition__c,Publisher__c,Total_Merchandise_QtyTotal_Qty__c,Status__c FROM Merchandise__c WHERE ID = :merchandise_id];          Inventory__c i = new Inventory__c(); //Line 1        List&lt;Inventory__c&gt; newInventory = new List&lt;Inventory__c&gt;();        for(Merchandise__c m : merchandise_collection )        {            if(m.Status__c !='Fully Converted')            {            i.Author__c = m.Author__c ;            i.Book_Title__c = m.Book_Title__c;            i.Edition__c = m.Edition__c;            i.Publisher__c = m.Publisher__c;            i.Qty_Available__c = m.Total_Merchandise_QtyTotal_Qty__c;            i.Merchandise__c = m.Id;            m.Uninventoried_Qty__c = 0;            m.Status__c = 'Fully Converted';            newInventory.add(i);            }        }        insert newInventory;        update merchandise_collection;    }  }   By moving the Line 1 to within the for loop solved the issue for me.  Thanks to this post (refer the Best Answer in that post)    What puzzles me is that WHY i have to instantiate "i" for every iteration within the loop.  Why the list collection ("newInventory") is complaining that are duplicate elements and why should it even confuse in the first place when I am performing an "insert" even ?
110175
I am receiving an error stated above on line 26**(listAccount1)**, can anyone guide me on how to solve it?  public class FRB_UpdateExceptionsforBatch {    public static void FRB_Exceptions(){    string FRBRecordTypeID = utility.getFRBProfileNameLabel();       List&lt;Account&gt; lstAccount = new List&lt;Account&gt;();         List&lt;Account&gt; lstAccount1 = new List&lt;Account&gt;();         List&lt;Account&gt; lstAccount2 = new List&lt;Account&gt;();         List&lt;Account&gt; lstAccount3 = new List&lt;Account&gt;();    lstAccount = [Select id,FRB_Firm_Check__c,Number_of_Exception__c,Number_of_exceptions_under_4_6_bucket__c,Number_of_exceptions_under_7_10_bucket__c,Number_of_exceptions_under_11_19_bucket__c,(select id,Account_Standing__c from Process_Adherence_Monitoring__r  where Status__C != 'Closed' AND  recordtypeId =: FRBRecordTypeID AND Account_Standing__c = '0-3 Days (Green - New Exception)' ) FROM Account WHERE FRB_Firm_Check__c = TRUE];     if(lstAccount.size()&gt;0){           for( Account acc : lstAccount )           {               List&lt;Process_Adherence_Monitoring__c&gt; lstCont = acc.Process_Adherence_Monitoring__r;                acc.Number_of_Exception__c = lstCont.size();               acc.FRB_Firm_Check__c = true;           }            update lstAccount;     }         //To update 4-6 bucket      lstAccount1 = [select Id, Name,FRB_Firm_Check__c, Number_of_exceptions_under_4_6_bucket__c,(select id,Account_Standing__c from Process_Adherence_Monitoring__r  where Status__C != 'Closed' AND  recordtypeId =: FRBRecordTypeID AND Account_Standing__c = '4-6 Days (Yellow - Outside Correction Timeframe)' ) from Account where FRB_Firm_Check__c = TRUE];        if(lstAccount1.size()&gt;0){           for( Account acc : lstAccount1 )           {               List&lt;Process_Adherence_Monitoring__c&gt; lstCont1 = acc.Process_Adherence_Monitoring__r;                              acc.Number_of_exceptions_under_4_6_bucket__c= lstCont1.size();               acc.FRB_Firm_Check__c = true;           }            update lstAccount1 ;       }         //To update 6-11 bucket         lstAccount2 =  [select Id, Name,FRB_Firm_Check__c, Number_of_exceptions_under_7_10_bucket__c,(select id,Account_Standing__c from Process_Adherence_Monitoring__r  where Status__C != 'Closed' AND  recordtypeId =: FRBRecordTypeID AND Account_Standing__c = '7-10 Days (Orange - Approaching Critical Timeframe)' ) from Account where FRB_Firm_Check__c = TRUE];        if(lstAccount2.size()&gt;0){           for( Account acc : lstAccount2 )           {               List&lt;Process_Adherence_Monitoring__c&gt; lstCont2 = acc.Process_Adherence_Monitoring__r;                acc.Number_of_exceptions_under_7_10_bucket__c= lstCont2.size();               acc.FRB_Firm_Check__c = true;           }           update lstAccount2 ;       }        //To update 11 bucket            lstAccount3 =  [select Id, Name,FRB_Firm_Check__c, Number_of_exceptions_under_11_19_bucket__c,(select id,Account_Standing__c from Process_Adherence_Monitoring__r  where Status__C != 'Closed' AND  recordtypeId =: FRBRecordTypeID AND Account_Standing__c = '11-19 Days (Red - Immediate Correction Required)' ) from Account where FRB_Firm_Check__c = TRUE];        if(lstAccount3.size()&gt;0){           for( Account acc : lstAccount3 )           {               List&lt;Process_Adherence_Monitoring__c&gt; lstCont3 = acc.Process_Adherence_Monitoring__r;                acc.Number_of_exceptions_under_11_19_bucket__c= lstCont3.size();               acc.FRB_Firm_Check__c = true;           }                              update lstAccount3 ;       }      }   }
54645
In the Java snippet:  SyndFeedInput fr = new SyndFeedInput(); SyndFeed sf = fr.build(new XmlReader(myInputStream)); List&lt;SyndEntry&gt; entries = sf.getEntries();   the last line generates the warning   "The expression of type List needs unchecked conversion to conform to List&lt;SyndEntry&gt;"  What's an appropriate way to fix this?