Converte Aray para List

7 respostas
P

Olá pessoal,

tem algum comando que consigo converter um array de string para lista.

Se alguém puder me ajudar …

abs

String[] texto ={"letra1","letra2","letra3"}

7 Respostas

Rafael_Nunes

List lista = Arrays.asList(texto); ou List lista = Arrays.asList("letra1", "letra2", "letra3");

T
List<String> lista = Arrays.asList (texto);

Cuidado - a lista acima é “imutável”, ou seja, você não pode acrescentar mais elementos nela.
Se precisar de uma lista “mutável”, então:

List<String> lista = new ArrayList<String>(Arrays.asList(texto));
alucardeck

nao lembro se tem um comando exatamente…
estou sem o eclipse aki para testar =P
mas um for resolve tudo…

String[] texto ={"letra1","letra2","letra3"} ;
ArrayList<String> txt = new ArrayList<String>();

for(int i = 0; i < texto.length(); i++){
    txt.add(text[i]);
}
Bravox
List<String> list = Arrays.asList(texto);
P

Olá pessoal,

mais duvida por que tras valor negativo qdo tito a linha sort…

abs

public class Test13 {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		 String [] sa = {"foo", "bar", "baz" };
		    // insert method invocations here
		 List lista = Arrays.asList(sa);  
		 //Collections.sort(lista);
		 for (int i = 0; i < sa.length; i++) {
			String string = sa[i];
			System.out.println(string);

		 }

		 int pos = Collections.binarySearch(lista, "foo"); 
		 System.out.println(pos);
	}

resultad:

foo
bar
baz
-4
alucardeck

Returns:
index of the search key, if it is contained in the list; otherwise, (-(insertion point) - 1). The insertion point is defined as the point at which the key would be inserted into the list: the index of the first element greater than the key, or list.size(), if all elements in the list are less than the specified key. Note that this guarantees that the return value will be >= 0 if and only if the key is found.

de acordo com a documentação…

pq não encontrou o “foo” procurado
-4 da “soma” de -3 com -1…

-3 pq eh o proximo index a ser inserido…
e -1 pq assim esta escrito lah =P

Rafael_Nunes

Porque a própria documentação do método fala isso.

Javadoc:

Searches the specified list for the specified object using the binary search algorithm. The list must be sorted into ascending order according to the natural ordering of its elements (as by the sort(List) method, above) prior to making this call. If it is not sorted, the results are undefined. If the list contains multiple elements equal to the specified object, there is no guarantee which one will be found.

Criado 10 de junho de 2008
Ultima resposta 10 de jun. de 2008
Respostas 7
Participantes 5