In this code i have implemented My own list model AbstractListModel to be able to add and remove elements to list adding works removing also, but i want here the elements to be added and removed like this: "add John", John is added to the list, same with removing. I splited string by delimeter and added it to my array of strings but it does not work, so here is my question how to add elements and remove by the delimeter.  import java.awt.*; import java.util.*; import javax.swing.*;     class MyListModel extends AbstractListModel&lt;String&gt; {       ArrayList&lt;String&gt; list = new ArrayList&lt;&gt;();      public int getSize() {     return list.size(); }  public String getElementAt(int index) {     return list.get(index); }  public int getIndexOfItem(String searchTerm) {     int z = 0;     for (int i=0;i &lt; list.size();i++) {         if (list.get(i).equals(searchTerm)){             z = i;         }     }     return z; }  public void add(String item) {     list.add(item);     fireIntervalAdded(this, list.size() - 1, list.size() - 1); }  public boolean remove(String name) {     boolean success = false;     int size = list.size();     for (int i=0;i &lt; size;i++) {        if (this.getElementAt(i).equals(name)) {         this.remove(i);         size--;         success = true;     }     }     return success; }  public void remove(int index) {     list.remove(index);     fireIntervalRemoved(this, index, index); }  public boolean isEmpty() {     boolean empty = false;     if (this.getSize() == 0) {         empty = true;     }     return empty; } }  public class JListl extends JFrame {  public JListl() {       MyListModel ml = new MyListModel();     JList list = new JList(ml);     add(new JScrollPane(list));       TextField tf = new TextField();            add(tf, BorderLayout.SOUTH);       this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);     this.setTitle("JList Renderer Example");     this.setSize(250, 400);     this.setLocationRelativeTo(null);     this.setVisible(true);     tf.addActionListener(new java.awt.event.ActionListener() {   public void actionPerformed(java.awt.event.ActionEvent e) {       //here is the problem      String[] a = tf.getText().split("\\s+");       // ml.add(a[1]);         if(a[0]=="add"){             tf.setSelectionStart(4);             tf.setSelectionEnd(a[1].length());            ml.add(a[1]);             System.out.println(a[1]);         }else if(a[0]=="del"){             ml.remove(a[1]);          }     } }); }  public static void main(String[] args) {     SwingUtilities.invokeLater(new Runnable() {         @Override         public void run() {             new JListl();         }     }); } }
93
I've been using the == operator in my program to compare all my strings so far. However, I ran into a bug, changed one of them into .equals() instead, and it fixed the bug.  Is == bad? When should it and should it not be used? What's the difference?
6996
How to add new item in existing string array in C#.net?  I need to preserve the existing data.
90357
I am trying to tidy up some really bad legacy code from an old developer and I'm trying to get rid of these nested for loops. The code below shows what I'm currently working with. I've fixed this before with nested SOQL queries but nothing like this. How would this need to look to remove these for loops (except Trigger.New)? Would I use Maps? How would I do that?  map&lt;Id,SObject&gt; mapProperyIdBudDetail = util.GetObjFields(setPropertyId, 'Property'); map&lt;Id,SObject&gt; mapSpaceIdBudDetail = util.GetObjFields( PropertyMap.keyset(), 'Space');  for ( Lease__c l: Trigger.New ) {      if(mapProperyIdBudDetail.get(PropertyMap.get(l.space__c))!=null) {          lProperties = new List&lt;SObject&gt;{mapProperyIdBudDetail.get(PropertyMap.get(l.space__c))};              for ( SObject p: lProperties ) {                  for ( String fm: FieldMap.keyset() ) {                      if ( p.get(FieldMap.get(fm)) != Null) {                         l.put(fm,p.get(FieldMap.get(fm)));                     }                  }             }     } }
11
I've always been one to simply use:  List&lt;String&gt; names = new ArrayList&lt;&gt;();   I use the interface as the type name for portability, so that when I ask questions such as these I can rework my code.    When should  be used over  and vice-versa?
1296
Why isn't  generic?    Seems like Collection&lt;E&gt; could have boolean remove(E o);   Then, when you accidentally try to remove (for example) Set&lt;String&gt; instead of each individual String from a Collection&lt;String&gt;, it would be a compile time error instead of a debugging problem later.
3046
Assuming I have an ArrayList  ArrayList&lt;MyClass&gt; myList;   And I want to call toArray, is there a performance reason to use  MyClass[] arr = myList.toArray(new MyClass[myList.size()]);   over  MyClass[] arr = myList.toArray(new MyClass[0]);   ?  I prefer the second style, since it's less verbose, and I assumed that the compiler will make sure the empty array doesn't really get created, but I've been wondering if that's true.  Of course, in 99% of the cases it doesn't make a difference one way or the other, but I'd like to keep a consistent style between my normal code and my optimized inner loops...
10572
Given an array of n Objects, let's say it is an array of strings, and it has the following values:  foo[0] = "a"; foo[1] = "cc"; foo[2] = "a"; foo[3] = "dd";   What do I have to do to delete/remove all the strings/objects equal to "a" in the array?
55036
I saw this reply from Jon on :     If you want a single collection to   contain multiple unrelated types of   values, however, you will have to use   List&lt;object&gt;   I'm not comparing ArrayList vs List&lt;&gt;, but ArrayList vs List&lt;object&gt;, as both will be exposing elements of type object. What would be the benefit of using either one in this case?  EDIT: It's no concern for type safety here, since both class is exposing object as its item. One still needs to cast from object to the desired type. I'm more interested in anything other than type safety.  EDIT: Thanks Marc Gravell and Sean for the answer. Sorry, I can only pick 1 as answer, so I'll up vote both.
53456
What is the difference between:  some_list1 = [] some_list1.append("something")   and  some_list2 = [] some_list2 += ["something"]
17166
I have a list of integers, List&lt;Integer&gt; and I'd like to convert all the integer objects into Strings, thus finishing up with a new List&lt;String&gt;.  Naturally, I could create a new List&lt;String&gt; and loop through the list calling String.valueOf() for each integer, but I was wondering if there was a better (read: more automatic) way of doing it?
57401
I have been working on a Java project for a class for a while now. It is an implementation of a linked list (here called AddressList, containing simple nodes called ListNode). The catch is that everything would have to be done with recursive algorithms. I was able to do everything fine sans one method: public AddressList reverse()      ListNode:    public class ListNode{   public String data;   public ListNode next; }   Right now my reverse function just calls a helper function that takes an argument to allow recursion.  public AddressList reverse(){   return new AddressList(this.reverse(this.head)); }   With my helper function having the signature of private ListNode reverse(ListNode current).  At the moment, I have it working iteratively using a stack, but this is not what the specification requires. I had found an algorithm in C that recursively reversed and converted it to Java code by hand, and it worked, but I had no understanding of it.  Edit: Nevermind, I figured it out in the meantime.  private AddressList reverse(ListNode current, AddressList reversedList){   if(current == null)        return reversedList;   reversedList.addToFront(current.getData());   return this.reverse(current.getNext(), reversedList); }   While I'm here, does anyone see any problems with this route?
33695
I have a Java bean like this:  class Person {   int age;   String name; }   I'd like to iterate over a collection of these beans in a JSP, showing each person in a HTML table row, and in the last row of the table I'd like to show the total of all the ages.  The code to generate the table rows will look something like this:  &lt;c:forEach var="person" items="${personList}"&gt;   &lt;tr&gt;&lt;td&gt;${person.name}&lt;td&gt;&lt;td&gt;${person.age}&lt;/td&gt;&lt;/tr&gt; &lt;/c:forEach&gt;   However, I'm struggling to find a way to calculate the age total that will be shown in the final row without resorting to scriptlet code, any suggestions?
76446
I would like to merge multiple List into one but I am not sure on how to do it .. My code is the following: public with sharing class ApprovalDashboard {     public ApprovalDashboard(){              }          @AuraEnabled(cacheable=true)     public static List&lt;Object&gt; approvalTableData(){         List&lt;Object&gt; FinalList = new List&lt;Object&gt;();         List&lt;AggregateResult&gt; OppList = [SELECT Opportunity__r.Id  FROM Approval__c                                       WHERE (Type__c = 'Investment_Committee' OR Type__c = 'Pre_IC')                                      AND Status__c != Null                                      AND CALENDAR_YEAR(Date__c) = 2021                                      GROUP BY Opportunity__r.Id];                  for(AggregateResult item: OppList){             List&lt;Opportunity&gt; OppData = [SELECT Id, Name, StageName                                          FROM Opportunity                                          WHERE Id = :item.Id];                          List&lt;Approval__c&gt;ApprovalList = [SELECT Name, date__c FROM Approval__c WHERE Opportunity__r.id = :item.Id];             system.debug(OppData);         }                                             return OppList;              }  I would like to mege OppData and ApprovalList into one big List in the format [{}, {},{}] .. Any help ?
52986
I am trying to add map of map values, I have to intialize the map key first and then try to add value later. Below is the exact logic i am trying to achieve.  Map&lt;string,Map&lt;string,List&lt;string&gt;&gt;&gt; finalMap = new Map&lt;string,Map&lt;string,List&lt;string&gt;&gt;&gt;();  Map&lt;string,List&lt;string&gt;&gt; subMap = new Map&lt;string,List&lt;string&gt;&gt;(); submap.put('One',new list&lt;string&gt;{'One','TWO'});  finalMap.put('SUB1',new Map&lt;string,List&lt;string&gt;&gt;());  //Do some logics and finally try to add the values with the key  finalmap.get('SUB1').put(subMap); //Error as stated below  System.debug(finalmap);      ERROR :Method does not exist or incorrect signature:   [Map&lt;String,List&lt;String&gt;&gt;].put(Map&lt;String,List&lt;String&gt;&gt;)
117983
I am trying to remove duplicate and creating a set and list with non duplicate values related to field ord__c . Trying to minimize the code as far as possible. Let me know if I can handle the same using the below piece of code I am using :   Set &lt; Id &gt; OrId = new Set &lt; Id &gt; ();  Integer j = 0;         while (j &lt; ListR.size())         {           OrId.add(ListR.get(j).Ord__c);           if(OrId.contains(ListR.get(j).Ord__c))           {             ListR.remove(j);           }           else           {             j++;           }         }
98687
If the user selects an option in a dropdown box, there must be added a label and a textbox. Using appendChild, these elements get added to the end of the container.  var newFreeformLabel = document.createElement('label'); newFreeformLabel.innerHTML = 'Omschrijving:';  var newFreeformField = document.createElement('input'); newFreeformField.className = 'textfield'; newFreeformField.name = 'factuur_orderregel[]';  var newFreeformSpacer = document.createElement('div'); newFreeformSpacer.className = 'spacer';  container.appendChild(newFreeformLabel); container.appendChild(newFreeformField); container.appendChild(newFreeformSpacer);   The issue is that these elements should be inserted at the beginning of container, not at the end.  Is there a solution to this in PrototypeJS?
9051
Check out the below program.   try {     for (String data : Files.readAllLines(Paths.get("D:/sample.txt"))){         String[] de = data.split(";");         System.out.println("Length = " + de.length);     } } catch (IOException e) {     e.printStackTrace(); }   Sample.txt:   1;2;3;4 A;B;; a;b;c;   Output:   Length = 4 Length = 2 Length = 3   Why second and third output is giving 2 and 3 instead of 4. In sample.txt file, condition  for 2nd and 3rd line is should give newline(\n or enter) immediately after giving delimiter for the third field. Can anyone help me how to get length as 4 for 2nd and 3rd line without changing the condition of the sample.txt file and how to print the values of de[2] (throws  ArrayIndexOutOfBoundsException)?