Форум программистов, компьютерный форум, киберфорум
Java SE (J2SE)
Войти
Регистрация
Восстановить пароль
Карта форума Темы раздела Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 5.00/7: Рейтинг темы: голосов - 7, средняя оценка - 5.00
2 / 2 / 2
Регистрация: 03.11.2013
Сообщений: 41
1

Как расширить массив, не используя arrays.copy

28.05.2015, 10:06. Показов 1393. Ответов 4
Метки нет (Все метки)

Author24 — интернет-сервис помощи студентам
Пробую написать метод для расширения масива при добавлении елемента по чсету большего чем размер масива. Но почему то не работает...выдает индекс оут оф бондс может кто подскажет? Создал новый метод который создает масив больше в 2 раза и копирует содержимое из старого в новый масив.
Вот здесь в add методе
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
 /**
 * This is class ArrayCharList which creates an Array
 * of chars and perform actions on it like inserting, removing
 * returning index of elements etc.
 * @author Oleksandr Gorkovets
 * @version May 27, 2015
 *
 */
public class ArrayCharList {
    private char[] cArray;
    private int size;
    //This is constant to represent the capacity of an array
    public static final int DEFAULT_CAPACITY = 10;
    //this is constructor
    public ArrayCharList(){
        this(DEFAULT_CAPACITY);
    }
    //this is second constructor which will use the 1st constructor
    //it throws an exception if user gives negative capacity for an array
    public ArrayCharList(int capacity) {
        if (capacity < 0){
            throw new IllegalArgumentException("capacity: " + capacity);
        }
        cArray = new char[capacity];
        size = 0;
    }
    /**
     * This method checks index of an element of it is in right range
     * from 0 to the size of an array 
     * @param i this is index of an element
     */
    private void checkIndex(int i){
        if (i < 0 || i >= size){
            throw new IndexOutOfBoundsException("index: " + i);
        }
    }
    /**
     * This method adds new char element to an array
     * also it checks if the size of occupied spaces is greater than 
     * array length
     * @param c char to be added
     */
    public void add(char c) {       
        if(size > cArray.length){           
            cArray = expandCapacity(cArray);
        }
        cArray[size] = c;
        size++;
    }
    /**
     * This method creates new array 2 times larger than default array
     * and copies all the lement into new array
     * @param cArray list passed as a parameter
     * @return new array 2 times larger
     */
    public char[] expandCapacity(char[] cArray){
        char[] larger = new char[cArray.length *2];
        for (int i = 0; i < cArray.length; i++){
            larger[i] = cArray[i];                      
        }
        return larger;
    }
 
    /**
     * This method returns size of occupied part an array
     * @return size as int
     */
    public int size() {     
        return size;
    }
    /**
     * This method returns an element at the specified index
     * @param i this is index of needed element
     * @return element as char
     */
    public char get(int i) {
        checkIndex(i);
        return cArray[i];       
    }
    /**
     * This method adds a char element at specified index 
     * @param i index where to add an element
     * @param c element to be added
     * @throws ArrayIndexOutOfBoundsException
     */
    public void add(int i, char c) throws ArrayIndexOutOfBoundsException {
        for (int j = size; j >= i + 1; j--){
            cArray[j] = cArray[j-1];
        }
        cArray[i] = c;
        size++;
    }
    
    /**
     * This method set new element at the specified index
     * @param i index where to set element
     * @param c element as char
     */
    public void set(int i, char c) {
        cArray[i] = c;      
    }
    /**
     * This method removes element at the specified index
     * @param i index where to remove element
     */
    public void remove(int i) {
        checkIndex(i);
        for (int j=i; j < size - 1; j++){
            cArray[j] = cArray[j+1];
        }
        //after element will be removed the size going to be decreased by 1
        size--;
        
    }
    /**
     * This method checks if the specified element is in an array
     * @param c char element 
     * @return true if element is in array or false  if not
     */
    public boolean contains(char c) {
        return indexOf(c) >= 0;     
    }
    /**
     * This method returns first index of an element in an array
     * @param c char element
     * @return index of element
     */
    public int indexOf(char c) {
        int count = 0;
        for(int j=0; j<cArray.length; j++){
            if(cArray[j] == c && count < 1){
                count++;
                return j;
            }           
        }
        return -1;
    }
    /**
     * This method returns the last index of an element in an array
     * @param c char element
     * @return index of the last element equal to c
     */
    public int lastIndexOf(char c) {
        
        int count = 0;
        for(int j=cArray.length-1; j>=0; j--){
            if(cArray[j] == c && count < 1){
                count++;
                return j;
            }           
        }
        return -1;
    }
    /**
     * This method checks if the occupied size is 0
     * @return true if it is empty ot false if not
     */
    public boolean isEmpty(){
        return size == 0;
    }
    /**
     * This method clears occupied spaces and make all spcaces of an array empty
     */
    public void clear(){
        size = 0;
    }
    /**
     * This method uses ArrayCharListIterator class to create new iterator
     * @return new iterator
     */
    public ArrayCharListIterator iterator(){
        return new ArrayCharListIterator(this);
    }
    /**
     * This method returns String version of an array
     */
    public String toString(){
        if (size ==0){
            return "[]";
        }
        else{
            String result = "[" + cArray[0];
            for (int i = 1; i< size; i++){
                result += ", " + cArray[i]; 
            }
            result += "]";
            return result;
        }
        
    }
 
}
0
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
28.05.2015, 10:06
Ответы с готовыми решениями:

Как расширить динамический массив НЕ используя stl
То есть создал я массив: int *arr = new int n-какое-то значение А дальше я хочу сделать...

Ошибка ? Nonscalar arrays of function handles are not allowed; use cell arrays instead
Вот код: function coeff=kerim_LL(x,L,ydata,w,t,f,step) for n=1:length(step); if...

Пункт Расширить том в Windows Vista Home Basic не активен - Как же расширить?
Товарищи, здравствуйте. Подскажите, пожалуйста, а как же расширить в Vista Home Basic том C...

как расширить массив
Привет.Как правильно расширить массив. Например. У меня есть массив и я вывел все отрицательные...

4
Автоматизируй это!
Эксперт Python
7107 / 4610 / 1215
Регистрация: 30.03.2015
Сообщений: 13,243
Записей в блоге: 29
28.05.2015, 16:58 2
galexik81, интересный проект! Сам делал подобное, только для примитивных числовых типов.
Ошибка тут, исправь
Java
1
if(size > cArray.length-1){
ну и с Итератором ты намудрил
1
2 / 2 / 2
Регистрация: 03.11.2013
Сообщений: 41
28.05.2015, 18:58  [ТС] 3
Спасибо большое, сам не пойму как это я не догнал сразу
Для итератора есть отдельный класс, в котором описаны методы next(), hasNext(), rewind() и remove() согласно заданию с такими условиями. Но хотелось бы понять свои ошибки поэтому принимаю любую критику)))
Вот клас итератора
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import java.util.*;
/**
 * This class defines and constructs iterator for array iteration
 * @author Oleksandr Gorkovets
 * @version May 27, 2015
 */
/**
 */
public class ArrayCharListIterator {
    private int position;
    private ArrayCharList list;
    private boolean removeOK;
    
    //This is constructor which takes a list as a parameter
    
    public ArrayCharListIterator(ArrayCharList list) {
        this.list = list;
        position = 0;
        removeOK = false;
    }
    /**
     * This method checks if there are more elements in an array to read
     * @return true if there are some elements or false if not
     */
    public boolean hasNext(){
        return position < list.size();
    }
    /**
     * This method reads next element of an array
     * also it records the last position read so next time it will be called 
     * it will read next element
     * @return next element as char
     */
    public char next(){
        if(!hasNext()){
            throw new NoSuchElementException();
        }
        char result = list.get(position);
        position++;
        removeOK = true;
        return result;
    }
    /**
     * This method removes element from an array
     */
    public void remove(){
        if (!removeOK){
            throw new IllegalStateException();
        }
        list.remove(position - 1);
        position--;
        removeOK = false;
    }
    
    /**
     * This method resets an iterator to 0 if needed
     */
    public void rewind() {
        position = 0;
        
    }
    
    
 
}
0
Автоматизируй это!
Эксперт Python
7107 / 4610 / 1215
Регистрация: 30.03.2015
Сообщений: 13,243
Записей в блоге: 29
28.05.2015, 19:26 4
galexik81, для новых вопросов новая тема...но сразу спрошу -вот этот твой код с итератором работает?
1
2 / 2 / 2
Регистрация: 03.11.2013
Сообщений: 41
28.05.2015, 19:30  [ТС] 5
Да, работает вроде нормально. Ок понял на счет новой темы.
0
28.05.2015, 19:30
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
28.05.2015, 19:30
Помогаю со студенческими работами здесь

Свой класс вектор. Как расширить динамический массив
#include &lt;iostream&gt; using namespace std; template&lt;typename T&gt; class Vector { private: int...

boost::copy для создания copy constructor and assignment operator
&lt;boost/iostreams/copy.hpp&gt; кто ниб использовал boost::copy для создания copy constructor and...

Arrays, как работает данная программа?
Как работает данная программа?! Как я понимаю должны выйти значения от 0 к 4.Как здесь удалось int...

Расширить массив из цифр
Нужно расширить старый массив чисел, из 4х чисел должно получиться 6 (берем входной блок из 4х...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
5
Ответ Создать тему
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2024, CyberForum.ru