Verificar se valor já está no array

11 respostas
O

Olá pessoal,

Gostaria de saber se antes de incluir um valor em um array é possível verificar se o mesmo já está lá, segue meu código:

Vector productListTmp = null;
        Vector productList = new Vector();

         for(int i=0; i<keys.length; i++)
         {
             if (keys[i]==null)
                continue;

             productListTmp = (Vector)orderProducts.get(keys[i].toString());
             productList.addAll(productList.size(), productListTmp);
         }

Quero que o productListTmp seja adicionado ao productList somente se ainda não estiver lá um valor igual.

Valeu!

11 Respostas

W

use alguma coleção que implemente Set (http://docs.oracle.com/javase/tutorial/collections/interfaces/set.html) e sobreescreva o equals/hashcode do seu objeto e problema resolvido.

[]'s

O

Legal, eu teria que ler muito a respeito, e como sou meio leigo ainda e tenho pouco tempo não daria, sei que não é da filosofia de um fórum pedir que façam, mas poderia me mostrar como eu poderia proceder?

Obrigado.

F

ueh, vc pode usar o contains()

veja.

public class TestaVector{
        private Vector<String> v = new Vector<String>();
        
        public TestaVector(){
             v.add("fernando");
             if(v.contains("fernando")){
                    v.add("paiva");
             } 
        }
}

t+ e boa sorte.

F

Procure usar ArrayList ao inves de Vector. Leia sobre Java Collections

t+ e boa sorte.

O

fiz assim mas não deu, ao imprimir o v ele está vazio

Vector productListTmp = null;
        Vector productList = new Vector();
		Vector<String> v = new Vector<String>();

         for(int i=0; i<keys.length; i++)
         {
             if (keys[i]==null)
                continue;

             productListTmp = (Vector)orderProducts.get(keys[i].toString());
			 if(!v.contains(productListTmp)){  
				productList.addAll(productList.size(), productListTmp);  
             }   
             
         }
V

Para usar o contains, você também precisa implementar o equals.

Aliás, você não deveria usar o Vector desde a versão 1.2 do Java. O substituto direto é a classe ArrayList:

V

Se seu produto é um String, então use o Set, como o colega falou:

Set&lt;String&gt; productSet = new TreeSet&lt;String&gt;();  
      
for(Object key : keys)  {  
   if (key ==null)  
      continue;   
   productListTmp = (Vector&lt;String&gt;)orderProducts.get(keys[i].toString());  
   productSet.addAll(productListTmp);    
}  
List&lt;String&gt; productList = new ArrayList&lt;String&gt;(productSet);
O

Essa instrução:

out.println(Arrays.asList(productList));

Me retorna isso:

[[ProductImpl{table_prefix='HYTC' parent_item_id=3304312 parent_item_number='AC3621LPEHCE' jpg_photo_name='aaa94426.jpg' section='|Enhanced Bathing|EB - Whirlpool Bath with Heater & Chromatherapy|' description='Langley(TM) 5' x 32" Enhanced Whirlpool Bath with Heater, Chromatherapy and Integral Apron, Left-hand Drain' brand_name='|Langley|' photo_caption='null' thumb_desc='Langley(TM) 5' x 32" Bath with Integral Apron' catalog_page='14.003.004' lifetime_warranty='null' similar_prod_desc='Bath with Integral Apron, Left-hand Drain' spec_pdf_file_name='|hytec_ac3621l_r_acr_bathtub_whirlpools.pdf|' ri_pdf_file_name='null' rm_pdf_file_name='null' sp_pdf_file_name='null' installation_pdf_file_name='null' cast_iron_warranty='null' db_zone='kldb_kldb_kohlerus_hytec' combined_dimensions='60" x 33-1/2"' brochure_pdf='null' buy_online_link='null' record_type='null' detail_graphic_1='null' image_gallery='null' flash_link='null'}, ProductImpl{table_prefix='HYTC' parent_item_id=3304312 parent_item_number='AC3621LPEHCE' jpg_photo_name='aaa94426.jpg' section='|Enhanced Bathing|EB - Whirlpool Bath with Heater & Chromatherapy|' description='Langley(TM) 5' x 32" Enhanced Whirlpool Bath with Heater, Chromatherapy and Integral Apron, Left-hand Drain' brand_name='|Langley|' photo_caption='null' thumb_desc='Langley(TM) 5' x 32" Bath with Integral Apron' catalog_page='14.003.004' lifetime_warranty='null' similar_prod_desc='Bath with Integral Apron, Left-hand Drain' spec_pdf_file_name='|hytec_ac3621l_r_acr_bathtub_whirlpools.pdf|' ri_pdf_file_name='null' rm_pdf_file_name='null' sp_pdf_file_name='null' installation_pdf_file_name='null' cast_iron_warranty='null' db_zone='kldb_kldb_kohlerus_hytec' combined_dimensions='60" x 33-1/2"' brochure_pdf='null' buy_online_link='null' record_type='null' detail_graphic_1='null' image_gallery='null' flash_link='null'}]]

Se observar bem sao dois resultados idênticos, é possível eliminar um deles caso seja igual ou já possua nessa lista?

V

Sem que você aprenda a usar os recursos da linguagem, não.

O

Ok, sei que devo aprender um pouco mais sobre os recursos, mas analisando esse trechoi não há nada que possa ser feito?

SearchResultsUtil sru = new SearchResultsUtil(products);
    Map orderProducts = sru.getOderedProducts();
    Product product=null;
    String pdf=null;
    String iipdf=null;
    Object[] keys = sru.getKeys();
    String rtm="";

    // Declarations needed for using stored procedures
    Connection procConn = null;
    int procErrorCode = -1;
    String procErrorMsg = null;
    PreparedStatement pStatement = null;
    

        Vector productListTmp = null;
		
        Vector productList = new Vector();

         for(int i=0; i<keys.length; i++)
         {
			if (keys[i]==null){
				continue;
			}
			
			productListTmp = (Vector)orderProducts.get(keys[i].toString());
			
			productList.addAll(productList.size(), productListTmp);
			
			
         }
O

EUREKA!

Criado 8 de fevereiro de 2012
Ultima resposta 8 de fev. de 2012
Respostas 11
Participantes 4