ArrayGrowTest
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package tp2; | |
/* | |
* Cay S. Horstmann & Gary Cornell, Core Java | |
* Published By Sun Microsystems Press/Prentice-Hall | |
* Copyright (C) 1997 Sun Microsystems Inc. | |
* All Rights Reserved. | |
* | |
* Permission to use, copy, modify, and distribute this | |
* software and its documentation for NON-COMMERCIAL purposes | |
* and without fee is hereby granted provided that this | |
* copyright notice appears in all copies. | |
* | |
* THE AUTHORS AND PUBLISHER MAKE NO REPRESENTATIONS OR | |
* WARRANTIES ABOUT THE SUITABILITY OF THE SOFTWARE, EITHER | |
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE | |
* IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A | |
* PARTICULAR PURPOSE, OR NON-INFRINGEMENT. THE AUTHORS | |
* AND PUBLISHER SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED | |
* BY LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING | |
* THIS SOFTWARE OR ITS DERIVATIVES. | |
*/ | |
/** | |
* @version 1.00 11 Mar 1997 | |
* @author Cay Horstmann | |
* @author Filip Krikava - few modifications for the purpose of the SE Lab | |
*/ | |
import java.lang.reflect.*; | |
import java.util.Arrays; | |
public class ArrayGrowTest { | |
/** | |
* Just a sample class | |
* | |
*/ | |
static class Personne { | |
private String nom; | |
public Personne(String nom) { | |
this.nom = nom; | |
} | |
public String toString() { | |
return nom; | |
} | |
} | |
public static void main(String[] args) { | |
int[] a = { 1, 2, 3 }; | |
Personne[] b = { new Personne("Maurice Chombier"), | |
new Personne("Francois Pignon") }; | |
// TODO: uncomment once goodArrayGrow is finished | |
// a = (int[]) goodArrayGrow(a); | |
// System.out.println(Arrays.toString(a)); | |
// b = (Personne[]) goodArrayGrow(b); | |
// System.out.println(Arrays.toString(b)); | |
System.out.println(Arrays.toString(badArrayGrow(b))); | |
System.out.println("The following call will generate an exception."); | |
b = (Personne[]) badArrayGrow(b); | |
} | |
// an intuitive solution that does not work | |
// there is a casting problem between Object[] and T[] | |
// since it creates new Object[] not new T[] | |
// where T is some type | |
private static Object[] badArrayGrow(Object[] a) { | |
int newLength = a.length * 2; | |
Object[] newArray = new Object[newLength]; | |
System.arraycopy(a, 0, newArray, 0, a.length); | |
return newArray; | |
} | |
// in order to make it work with priminitive types like (int[]) the | |
// parameter type has to be Object | |
private static Object goodArrayGrow(Object a) { | |
// TODO: write the code that grows the array by 2 | |
return null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment