Help with java arrays

Asked

Viewed 142 times

2

I have the discipline array and the current array.

The current one is an exact copy of the disciplines. If there are two equal Strings within the disciplines array I need to delete all the same and keep only one.

That is, the current should not contain repeated strings.

Can anyone help with this code?

String coisa = "";
String[] atual = disciplina.clone();;
int conta = 0;
for (int j = 0; j < disciplina.length; j++) {
  if (disciplina[j] != null && nota[j] != 0) {
      if(atual[j].equals(disciplina[j])){
        atual[j] = "";
      }
  }
  • Both are ArrayList of String?

  • are not arraylists, I am not using Collections, only arrays

  • 4

    Why You Can’t Use Collections?

  • It’s college exercise, probably.

  • Has any response helped solve the problem and can address similar questions from other users? If so, make sure to mark the answer as accepted. To do this just click on the left side of it (below the indicator of up and down votes).

3 answers

3

You can use the Set which does not allow duplicates.

Set<String> disciplinas = new HashSet<>(Arrays.asList(disciplina));

disciplina = disciplinas.toArray(new String[disciplinas.size()]);

Set

A Collection that contains no Uplicate Elements. More formally, sets contain no pair of Elements E1 and E2 such that E1.equals(E2), and at Most one null element. As implied by its name, this interface models the Mathematical set abstraction.

In free translation:

A collection that does not contain duplicate items. More formally, sets do not contain pairs of E1 and E2 elements in case of E1.equals(E2). As the name suggests, this interface is an abstraction of the mathematical model "set".


A resolution suggestion without using Collection:

public String[] removerDuplicados(String[] base) {
  String[] resultado = new String[base.length];
  int contador = 0;
  boolean encontrado;

  for (int i = 0; i < base.length; i++) {
    String elemento = base[i];

    encontrado = false;

    for (int j = 0; j < resultado.length; j++) {
      if (resultado[j] == null) {
        break;
      }

      if (resultado[j].equals(elemento)) {
        encontrado = true;
      }
    }

    if (!encontrado) {
      resultado[contador] = elemento;
      contador++;
    }
  }

  return Arrays.copyOfRange(resultado, 0, contador);
}

Another way is to order the array and then just compare with the previous record to insert into one another, without the duplicates:

public String[] removerDuplicados(String[] base) {
  String[] resultado = new String[base.length];
  String anterior = null;
  int indice = 0;

  Arrays.sort(base);

  for (String atual : base) {
    if (atual != null && (anterior == null || !atual.equals(anterior))) {
      resultado[indice] = atual;
      indice++;
    }

    anterior = atual;
  }

  return Arrays.copyOfRange(resultado, 0, indice);
}

Apply the above two methods as follows:

disciplina = removerDuplicados(disciplina);
  • I have to do only with array, type String

  • @cicada3301 this information is not included in your question, but I have put two more alternatives that may meet what you are looking for.

  • 1

    Thank you for showing the solution o(n log n)! I was feeling bad about not having this solution

  • 1

    @Jeffersonquesado I just don’t know if I use the java.utils.Arrays is allowed to use it, but then it implements in hand the sort right

  • 1

    I was gonna take a merge sort that I have another answer =) But this solution already meets my wishes perfectly

  • @Jeffersonquesado but you were with the same doubt?

Show 1 more comment

2


public static void main(String[] args) {
    String[] a = {"teste1", "teste2", "teste1"};
    String[] b = new String[a.length];
    for(int i = 0; i < a.length; i++) {
        if(arrayNaoContemString(b, a[i])) {
            b[i] = a[i]; 
        }
    }
    for (String string : b) {
        System.out.println(string);
    }
}

public static boolean arrayNaoContemString(String[] array, String string){
   for(String s : array){
       if (string.equals(s)){
           return false;
       }
   }
   return true;
}

See the result in Ideone. Or see this question in SO-en for more solutions.

  • 1

    Only beware of null pointer, if the argument of arrayNaoContemString be void

  • 1

    Yes, but it is very restricted the use of the method, so I did not find it necessary to put.

  • 1

    And most likely in this exercise there will never be a null entry. But I always believe it is auspicious to raise that one is assuming certain input or what the limitations of the solution. You kind of agree with Physics Girl on this video https://youtu.be/oxbuFwW5f-Q

1

Try this:

if (!atual.contains(disciplina[j])){
    atual.add(disciplina[j])
}

So in case the array atual does not contain the content of discplina[j] he will add

  • contains can only be used in arraylist, in which case I am only using string array, without Collections

Browser other questions tagged

You are not signed in. Login or sign up in order to post.