Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //MyArray.java
- /* Copyright (c) 2013 Elias Daler
- This software is provided 'as-is', without any express or implied
- warranty. In no event will the authors be held liable for any damages
- arising from the use of this software.
- Permission is granted to anyone to use this software for any purpose,
- including commercial applications, and to alter it and redistribute it
- freely, subject to the following restrictions:
- 1. The origin of this software must not be misrepresented; you must not
- claim that you wrote the original software. If you use this software
- in a product, an acknowledgment in the product documentation would be
- appreciated but is not required.
- 2. Altered source versions must be plainly marked as such, and must not be
- misrepresented as being the original software.
- 3. This notice may not be removed or altered from any source
- distribution.
- */
- import java.lang.reflect.Array;
- public class MyArray<T> {
- private T[] arr;
- private int size;
- @SuppressWarnings({"unchecked"})
- public MyArray(int s) {
- if(s <= 0) {
- throw new IndexOutOfBoundsException();
- }
- arr = (T[])new Object[s];
- size = s;
- }
- public void insert(T item, int index) {
- if(index >= size || index < 0) {
- throw new ArrayIndexOutOfBoundsException();
- }
- arr[index] = item;
- }
- public void insert(T item) {
- T[] arr_new = (T[])new Object[size + 1]; // create bigger array
- arr_new[size] = item; // insert item in the end
- for(int i = 0; i < size; i++) { // copy old array
- arr_new[i] = arr[i];
- }
- arr = arr_new;
- size++;
- }
- public T get(int index) {
- if(index >= size || index < 0) {
- throw new ArrayIndexOutOfBoundsException();
- }
- return arr[index];
- }
- public void remove(int index) {
- if(index >= size || index < 0) {
- throw new ArrayIndexOutOfBoundsException();
- }
- arr[size] = null;
- }
- public int size() {
- return size;
- }
- public String toString() {
- String str = new String();
- for(int i = 0; i < size; i++) {
- if(arr[i] != null) {
- str += arr[i].toString();
- if(i != size - 1) str += ", "; // don't add comma in the end
- } else {
- str += "null, ";
- }
- }
- return str;
- }
- @Override
- public boolean equals(Object o) {
- if(!(o instanceof MyArray)) return false;
- MyArray<T> second = (MyArray<T>)o;
- if(size != second.size()) {
- return false;
- }
- for(int i = 0; i < size; i++) {
- if(arr[i] != second.get(i)) return false;
- }
- return true;
- }
- public int hashCode() {
- return arr.hashCode();
- }
- }
- // main.java
- public class Main {
- public static void main(String[] args) {
- MyArray<Integer> test = new MyArray<Integer>(10);
- test.insert(5, 2);
- test.insert(10, 3);
- test.insert(20);
- System.out.println(test.toString());
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement