SóProvas


ID
215827
Banca
IF-SE
Órgão
IF-SE
Ano
2010
Provas
Disciplina
Programação
Assuntos

Considere as classes A e B apresentadas abaixo. O corpo de cada classe foi propositadamente omitido. class A implements Comparable { ... } class B extends A { ... } Considere dois objetos a e b, instâncias de Arrays das classes A e B, respectivamente. Baseado nessas declarações, assinale a alternativa que possui uma chamada que produz um erro, seja de compilação ou de execução.

Alternativas
Comentários
  • Letra E
    Java.util.Arrays.fill
    Fonte:http://www.javadocexamples.com/java/util/Arrays/fill(boolean%5B%5D%20a,boolean%20val).html

  • o correto seria  java.util.Arrays.fill (b,a[x]) onde x é o índice na Array A;


    http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Arrays.html#fill(java.lang.Object[], java.lang.Object)

    fill

    public static void fill(Object[] a,                        Object val)
    Assigns the specified Object reference to each element of the specified array of Objects.

     

    Parameters:
    a - the array to be filled.
    val - the value to be stored in all elements of the array.







     
  • Um sort iria ordenar o array b baseado em que informação? Se puder me infomar por recado, agradeço.
  • Breno, a ordenação do array depende da maneira como a classe A implementou o método compareTo da interface Comparable.

    Segue um exemplo.

    public Conta implements Comparable {
       
      private int numero;
      private String titular;
      // outros metodos e atributos
     
      public int compareTo(Conta outraConta) {
      if (this.numero < outraConta.numero) {
          return -1;
      }
      if (this.numero > outraConta.numero) {
          return 1;
      }
      return 0;
      }
    }

    No código acima, observe que o atributo numero é usado para a comparação. Se o numero é menor que de outra conta, retorna -1, se maior, retorna 1, se igual retorna 0. Assim, se você tivesse o código abaixo, ele utilizaria o atributo numero para ordenar.

    Conta[] arrayConta = new arrayConta[3];

    Conta c1 = new Conta();

    c1.numero = 3;

    Conta c2 = new Conta();

    c2.numero = 8;

    Conta c3 = new Conta();

    c3.numero = 1;

    arrayConta[0] = c1;

    arrayConta[1] = c2;

    arrayConta[2] = c3;

    java.util.Arrays.sort(arrayConta) reordena da seguinte forma: arrayConta[0]=c3;arrayConta[1]=c1; arrayConta[2]=c2. 

  • Alguém poderia exemplificar com clareza do porque a letra E?

  • @Willie Weeks

    A questão é trabalhosa mas, vamos lá

    a)  java.utils.Arrays.sort(b): Funciona pois, a classe implementa a interface comparable, ou seja, em algum momento ela implementa o método compareTo(Object object) que é herdado pela classe b. Conforme trecho da documentação do Java.util.arrays.sort(Object o)

    Sorts the specified array of objects into ascending order, according to the natural ordering of its elements. All elements in the array must implement the Comparable interface. Furthermore, all elements in the array must be mutually comparable (that is, e1.compareTo(e2) must not throw a ClassCastException for any elements e1 and e2 in the array).

    b) java.util.Arrays.toString(a): este método ira mostrar um valor de string do método caso tenha sido sobrescrito, ou a referência da memória onde o objeto a está alocado

    c) java.util.Arrays.equals(a,b): Conforme trecho da documentação do método equals(Object[] a, Object[] b)  Java abaixo

    Returns true if the two specified arrays of Objects are equal to one another. The two arrays are considered equal if both arrays contain the same number of elements, and all corresponding pairs of elements in the two arrays are equal. Two objects e1 and e2 are considered equal if (e1==null ? e2==null : e1.equals(e2)). In other words, the two arrays are equal if they contain the same elements in the same order. Also, two array references are considered equal if both are null.

    Parameters:

    a - one array to be tested for equality

    a2 - the other array to be tested for equality

    Returns:

    true if the two arrays are equal

    d) java.util.Arrays.binarySearch(a,b[0]): De acordo com a documentação do método public static int binarySearch(Object[] a, Object key) 

    Searches the specified array for the specified object using the binary search algorithm. The array must be sorted into ascending order according to the natural ordering of its elements (as by the sort(Object[]) method) prior to making this call. If it is not sorted, the results are undefined. (If the array contains elements that are not mutually comparable (for example, strings and integers), it cannot be sorted according to the natural ordering of its elements, hence results are undefined.) If the array contains multiple elements equal to the specified object, there is no guarantee which one will be found.

    Parameters:

    a - the array to be searched

    key - the value to be searched for

    Throws:

    ClassCastException - if the search key is not comparable to the elements of the array.

    Ou seja, existe uma possibilidade se ser a D visto que o corpo das classes foi omitido a exceção pode ocorrer.

     e) Conforme explicado pelo Fabiano Falcao, a assinatura do método na alternativa está errada pois, o correto é fillpublic static void fill(Object[] a, Object val) Assigns the specified Object reference to each element of the specified array of Objects.

    Pelo enunciado da questão como foi pedido um erro de compilação ou de execução, entendo que o erro de compilação tem prioridade maior. Por isso, letra E.