Link to home
Create AccountLog in
Avatar of jkteater
jkteaterFlag for United States of America

asked on

Eclipse Warning

I have 47 warnings in my code.  All of the warnings are basically the same with some differences

Warning A
The constructor TreeSet(Comparator) belongs to the raw type TreeSet. References to generic type TreeSet<E> should be parameterized


Warning B
The method add(Object) belongs to the raw type TreeSet. References to generic type TreeSet<E> should be parameterized

Warning C
The method addAll(Collection) belongs to the raw type TreeSet. References to generic type TreeSet<E> should be parameterized      
      
      

I know that I can set the compiler not to find the warnings, but I really need to fix the code.  I work with other programmers and the goal is to get our code without warnings so we know it is solid.

I am very new to java and eclipse, so this is very important to get solved.  I have read many articles without much success.  I have also ask a similar question here, but I thought I could find them, but had no luck.

Below is a piece code that has 3 of the 47 warnings

Please Help and show me how to fix them then maybe I can fix the rest.


public class SortingListModel extends AbstractListModel
    {
      
        private static final long serialVersionUID = 1L;
     
        TreeSet model;
        
    	private Comparator USEFUL_COMPARATOR = new Comparator()
            {
                public int compare( Object o1, Object o2 )
                {
                    String str1 = o1.toString();
                    String str2 = o2.toString();
                    Collator collator = Collator.getInstance();
                    int result = collator.compare( str1, str2 );
                    return result;
                }
            };

    public SortingListModel()
    {
Warning A===>model = new TreeSet( USEFUL_COMPARATOR );
    }
   
    public int getSize()
    {
         return model.size();
    }

    public Object getElementAt( int index )
    {        
        return model.toArray()[index];
    }
    
    public void addElement( Object element )
    {
        
Warning B===>if( model.add(element))
        {
            fireContentsChanged( this, 0, getSize() );
        }
    }

    public void addAll( Object elements[] )
    {
        Collection c = Arrays.asList(elements);
Warning C===>model.addAll(c);
        fireContentsChanged( this, 0, getSize() );
    }

    public void clear()
    {
        model.clear();
        fireContentsChanged( this, 0, getSize() );
    }

    public boolean contains( Object element )
    {
        return model.contains( element );
    }

    public Object firstElement()
    {
        return model.first();
    }

    public Iterator iterator()
    {
        return model.iterator();
    }

    public Object lastElement()
    {
        
        return model.last();
    }

    public boolean removeElement( Object element )
    {
        boolean removed = model.remove( element );
        if( removed )
        {
            fireContentsChanged( this, 0, getSize() );
        }
        return removed;
    }
 }

Open in new window

Avatar of Mick Barry
Mick Barry
Flag of Australia image

you need to define what type of objects are in your collextions

eg


        TreeSet<String> model;

...

model = new TreeSet<String>( USEFUL_COMPARATOR );


etc
Avatar of jkteater

ASKER

Yep I address this a day or two ago and I tried the define treeset <string> model - it did not fix my problem
its need to resolve you're warnings. Make those changes and let me know what warnings you have left
Sure

model.addAll(c);
Warning
The expression of type Collection needs unchecked conversion to conform to Collection<? extends String>      

if( model.add(element))
Error
The method add(String) in the type TreeSet<String> is not applicable for the arguments (Object)

model = new TreeSet<String>( USEFUL_COMPARATOR );
Warning
The expression of type Comparator needs unchecked conversion to conform to Comparator<? super String>      
you're comparator should be:

      private Comparator<String> USEFUL_COMPARATOR = new Comparator<String>() {
            public int compare(String o1, String o2) {
                  String str1 = o1.toString();
                  String str2 = o2.toString();
                  Collator collator = Collator.getInstance();
                  int result = collator.compare(str1, str2);
                  return result;
            }
      };

Do you actually need locale specific sorting?
And why are you using a Set to store what is actually a List?
(And using a TreeSet is actually messy there, forces you to refresh the whole list everytime you change a single element)
>       public void addElement(Object element) {

should be:


      public void addElement(String element) {

>       public void addAll(Object elements[]) {

same here


      public void addAll(String elements[]) {
Let me show you the complete code and any suggestions is great.  I am sorting email addresses when a user adds or removes one.
public class VendorEmailDialog extends JDialog {
  
   private static final long serialVersionUID = 1L;
   final SortingListModel model = new SortingListModel();
   private EdiProject  project = null;
   JLabel label;
   private JPanel centerPanel = null;
   JPanel cards;
   protected JTextField textField;
 
//////////////////////////////////////////////////////////////////////////
//                                                                      //
//                              Constructor                             //
//                                                                      //
//////////////////////////////////////////////////////////////////////////
   
   public VendorEmailDialog(TransmittalInfo reqTransInfo,EdiProject currentProject, Dialog parent, TCSession theSession, Registry theRegistry){
        
   super(parent,"Vendor Email Dialog", true);
   project = currentProject;
   createDialog();
   } 
    
//////////////////////////////////////////////////////////////////////////
//                                                                      //
//                             createDialog()                           //
//                                                                      //
//////////////////////////////////////////////////////////////////////////
    
    public SortingListModel getModel() {
	return model;
    }
    
    private void createDialog() {
    	
    	Component listPanel = EmailList();
    	Component buttonPanel = OKCancelButtons();
    	    	
    	centerPanel = new JPanel();
        centerPanel.setLayout(new BoxLayout(centerPanel, BoxLayout.PAGE_AXIS));
        centerPanel.setPreferredSize(new Dimension(600, 200));

        centerPanel.add(Box.createRigidArea(new Dimension(5, 0)));
        centerPanel.add(listPanel);
        centerPanel.add(Box.createHorizontalGlue());
        centerPanel.add(Box.createRigidArea(new Dimension(0, 2)));
        centerPanel.add(buttonPanel);
        
        getContentPane().add(centerPanel);
       
        addComponentListener(new ComponentAdapter() {
          public void componentResized(ComponentEvent event) {
             Component c = event.getComponent();
             c.setSize(Math.max((int)centerPanel.getPreferredSize().getWidth()/2, c.getWidth()),
                       Math.max((int)centerPanel.getPreferredSize().getHeight()/2, c.getHeight()));
          }
        });
    	  	
        this.pack();
        setLocation(getParent().getLocation(null));
        centerPanel.setVisible(true);
     }
      
//////////////////////////////////////////////////////////////////////////
//                                                                      //
//                             set_gbc()                                //
//                          GridBagConstraints                          //
//////////////////////////////////////////////////////////////////////////

    GridBagConstraints gbc = new GridBagConstraints();
	protected boolean alreadyEnabled;
    
    private void set_gbc(int row, int column, int width, int height, int fill) {
    	   gbc.gridy = row;
    	   gbc.gridx = column;
    	   gbc.gridwidth = width;
    	   gbc.gridheight = height;
    	   gbc.fill = fill;   
    }
   
//////////////////////////////////////////////////////////////////////////
//                                                                      //
//                             Validating Email                         //
//                                                                      //
//////////////////////////////////////////////////////////////////////////
    
    public boolean isValidEmailAddress(String emailAddress){  
    String  expression="^[\\w\\-]([\\.\\w])+[\\w]+@([\\w\\-]+\\.)+[A-Z]{2,4}$";  
    CharSequence inputStr = emailAddress;  
    Pattern pattern = Pattern.compile(expression,Pattern.CASE_INSENSITIVE);  
    Matcher matcher = pattern.matcher(inputStr);  
    return matcher.matches();  
    }      
    
//////////////////////////////////////////////////////////////////////////
//                                                                      //
//                             EmailList()                              //
//                                                                      //
//////////////////////////////////////////////////////////////////////////
    
    private JPanel EmailList(){
    	 
    	final JTextField addEmail = new JTextField(20);
    	JLabel eLabel = new JLabel("Additional Emails");
    	JLabel ListLabel = new JLabel("Existing Vendor Emails");
    	
    	String[] emails = project.getEmailAddresses();	    	
 
    	for (int i = 0; i < emails.length; ++i) {
         	 model.addElement(emails[i]);      
        }    	    	
               
        final JList AltList = new JList(model);
    	AltList.setBorder(BorderFactory.createLoweredBevelBorder());
    	AltList.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
    	AltList.setLayoutOrientation(JList.VERTICAL);
    	AltList.setVisibleRowCount(4);
    	JScrollPane acrossScrollBar= new JScrollPane(AltList); 
     	    	    	
    	final JButton addButton = new JButton("Add >>");
    	addButton.setEnabled(true);
        addButton.addActionListener(new ActionListener() {
        
        public void actionPerformed(ActionEvent e) {
           String name = addEmail.getText();
       
           if(isValidEmailAddress(name)) {  
        		  
        	  Component object = null;
        	  if (name.equals("") || alreadyInList(name)) {
        	       Toolkit.getDefaultToolkit().beep();
        	       JOptionPane.showMessageDialog(object,name + "Email Address Already In List");
        		   addEmail.requestFocusInWindow();
        		   addEmail.selectAll();
        		   return;
        	   }

        	   int index = AltList.getSelectedIndex(); 
        	   if (index == -1) { 
        		   index = 0;
        	   } 
        	   else {           
                  index++;
        	   }
        	   model.addElement(addEmail.getText());
        	   addEmail.requestFocusInWindow();
       		   addEmail.setText("");
       		   AltList.setSelectedIndex(index);
       		   AltList.ensureIndexIsVisible(index);
       	   }
       	   else{  
       		   Component object = null;
       		   JOptionPane.showMessageDialog(object,name + "Is not valid Email Address");
       	   }  
        }
        
           protected boolean alreadyInList(String name) {
               return model.contains(name);
           }
  
        });
 
        final JButton removeButton = new JButton("Remove <<");
        removeButton.setPreferredSize(new Dimension(100, 40));
        removeButton.setEnabled(true);
        removeButton.addActionListener(
        new ActionListener() {
           public void actionPerformed( ActionEvent event )
          {
        	   int index = AltList.getSelectedIndex();
               Object str = model.getElementAt(index);
        	    
               model.removeElement(str);
               int size = model.getSize();

               if (size == 0) { 
                   removeButton.setEnabled(false);

               } else { 
                   if (index == model.getSize()) {
                       index--;
                   }
                   AltList.setSelectedIndex(index);
                   AltList.ensureIndexIsVisible(index);
               }   
          }           
         });
      
        JPanel p = new JPanel();
        GridBagLayout gridbag = new GridBagLayout();
        p.setLayout(gridbag);
        
        gbc.insets = new Insets(5,10,10,5);      
        set_gbc(0, 0, 1, 1,GridBagConstraints.BOTH );
        gridbag.setConstraints(eLabel, gbc);
        p.add(eLabel);
        
        set_gbc(0, 2, 1, 1,GridBagConstraints.BOTH );
        gridbag.setConstraints(ListLabel, gbc);
        p.add(ListLabel);
               
        set_gbc(1, 0, 1, 1,GridBagConstraints.HORIZONTAL);
        gridbag.setConstraints(addEmail, gbc);
        p.add(addEmail);
                
        set_gbc(1, 2, 1, 3, GridBagConstraints.HORIZONTAL);
        gbc.anchor = GridBagConstraints.PAGE_END; 
        gbc.weightx = 3.0;
        gridbag.setConstraints(acrossScrollBar, gbc);
        p.add(acrossScrollBar);
              
        set_gbc(1, 1, 1, 1,GridBagConstraints.BOTH);
        gridbag.setConstraints(addButton, gbc);
        p.add(addButton);
        
        set_gbc(2, 1, 1, 1, GridBagConstraints.BOTH);
        gridbag.setConstraints(removeButton, gbc);
        p.add(removeButton);
                                    
        return p;
 }

//////////////////////////////////////////////////////////////////////////
//                                                                      //
//                        SortingListModel                              //
//                                                                      //
//////////////////////////////////////////////////////////////////////////  
    
    public class SortingListModel extends AbstractListModel
    {
      
        private static final long serialVersionUID = 1L;
     
        TreeSet<String> model;
        
    	private Comparator USEFUL_COMPARATOR = new Comparator()
            {
                public int compare( Object o1, Object o2 )
                {
                    String str1 = o1.toString();
                    String str2 = o2.toString();
                    Collator collator = Collator.getInstance();
                    int result = collator.compare( str1, str2 );
                    return result;
                }
            };

    public SortingListModel()
    {
         model = new TreeSet<String>( USEFUL_COMPARATOR );
    }
   
    public int getSize()
    {
         return model.size();
    }

    public Object getElementAt( int index )
    {        
        return model.toArray()[index];
    }
    
    public void addElement( String element )
    {
        
        if( model.add(element.toString()))
        {
            fireContentsChanged( this, 0, getSize() );
        }
    }

    public void addAll( String elements[] )
    {
        Collection<String> c = Arrays.asList(elements);
        model.addAll(c);
        fireContentsChanged( this, 0, getSize() );
    }

    public void clear()
    {
        model.clear();
        fireContentsChanged( this, 0, getSize() );
    }

    public boolean contains( Object element )
    {
        return model.contains( element );
    }

    public Object firstElement()
    {
        return model.first();
    }

    public Iterator iterator()
    {
        return model.iterator();
    }

    public Object lastElement()
    {
        
        return model.last();
    }

    public boolean removeElement( Object element )
    {
        boolean removed = model.remove( element );
        if( removed )
        {
            fireContentsChanged( this, 0, getSize() );
        }
        return removed;
    }
 }
   
//////////////////////////////////////////////////////////////////////////
//                                                                      //
//                        OKCancelButtons()                             //
//                                                                      //
//////////////////////////////////////////////////////////////////////////
    
    private JPanel OKCancelButtons() {
       JButton okButton = new JButton("OK");
       okButton.setEnabled(true);
       okButton.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent e) {
        	  getModel();  
          }
       });

       JButton cancelButton = new JButton("Cancel");
       cancelButton.setEnabled(true);
       cancelButton.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent e) {
             dispose();
          }
       });

       JPanel p = new JPanel();
       p.setLayout(new BoxLayout(p, BoxLayout.LINE_AXIS));
       p.add(Box.createHorizontalGlue());
       p.add(okButton);
       p.add(cancelButton);
     
       return p;
    }  
}

Open in new window

stepping out for a bit - be back in a while
I already answered this (which you ignored) at http:Q_26909703.html#35210216
I did not ignore your answer, I am trying to learn how to genericise all collection classes.  I can not figure out how to do it.  It seems like anything I change just breaks it somewhere else.  That is why I opened this question.  I wanted someone to show me how to do it, so I can do the rest of the warnings.
Please post code. You probably mostly just need <String> throughout, since that's what you're storing
ASKER CERTIFIED SOLUTION
Avatar of Mick Barry
Mick Barry
Flag of Australia image

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer