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

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

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

Студворк — интернет-сервис помощи студентам
Пробую написать метод для расширения масива при добавлении елемента по чсету большего чем размер масива. Но почему то не работает...выдает индекс оут оф бондс может кто подскажет? Создал новый метод который создает масив больше в 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
Эксперт
39485 / 9562 / 3019
Регистрация: 12.04.2006
Сообщений: 41,671
Блог
28.05.2015, 10:06
Ответы с готовыми решениями:

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

Ошибка ? 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 step(1,n)+length(L)-1&gt;length(ydata) ...

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

4
Автоматизируй это!
Эксперт Python
 Аватар для Welemir1
7391 / 4818 / 1246
Регистрация: 30.03.2015
Сообщений: 13,687
Записей в блоге: 29
28.05.2015, 16:58
galexik81, интересный проект! Сам делал подобное, только для примитивных числовых типов.
Ошибка тут, исправь
Java
1
if(size > cArray.length-1){
ну и с Итератором ты намудрил
1
2 / 2 / 2
Регистрация: 03.11.2013
Сообщений: 41
28.05.2015, 18:58  [ТС]
Спасибо большое, сам не пойму как это я не догнал сразу
Для итератора есть отдельный класс, в котором описаны методы 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
 Аватар для Welemir1
7391 / 4818 / 1246
Регистрация: 30.03.2015
Сообщений: 13,687
Записей в блоге: 29
28.05.2015, 19:26
galexik81, для новых вопросов новая тема...но сразу спрошу -вот этот твой код с итератором работает?
1
2 / 2 / 2
Регистрация: 03.11.2013
Сообщений: 41
28.05.2015, 19:30  [ТС]
Да, работает вроде нормально. Ок понял на счет новой темы.
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
inter-admin
Эксперт
29715 / 6470 / 2152
Регистрация: 06.03.2009
Сообщений: 28,500
Блог
28.05.2015, 19:30
Помогаю со студенческими работами здесь

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

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

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

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

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


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

Или воспользуйтесь поиском по форуму:
5
Ответ Создать тему
Новые блоги и статьи
Символьное дифференцирование
igorrr37 13.02.2026
/ * Программа принимает математическое выражение в виде строки и выдаёт его производную в виде строки и вычисляет значение производной при заданном х Логарифм записывается как: (x-2)log(x^2+2) -. . .
Камера Toupcam IUA500KMA
Eddy_Em 12.02.2026
Т. к. у всяких "хикроботов" слишком уж мелкий пиксель, для подсмотра в ESPriF они вообще плохо годятся: уже 14 величину можно рассмотреть еле-еле лишь на экспозициях под 3 секунды (а то и больше),. . .
И ясному Солнцу
zbw 12.02.2026
И ясному Солнцу, и светлой Луне. В мире покоя нет и люди не могут жить в тишине. А жить им немного лет.
«Знание-Сила»
zbw 12.02.2026
«Знание-Сила» «Время-Деньги» «Деньги -Пуля»
SDL3 для Web (WebAssembly): Подключение Box2D v3, физика и отрисовка коллайдеров
8Observer8 12.02.2026
Содержание блога Box2D - это библиотека для 2D физики для анимаций и игр. С её помощью можно определять были ли коллизии между конкретными объектами и вызывать обработчики событий столкновения. . . .
SDL3 для Web (WebAssembly): Загрузка PNG с прозрачным фоном с помощью SDL_LoadPNG (без SDL3_image)
8Observer8 11.02.2026
Содержание блога Библиотека SDL3 содержит встроенные инструменты для базовой работы с изображениями - без использования библиотеки SDL3_image. Пошагово создадим проект для загрузки изображения. . .
SDL3 для Web (WebAssembly): Загрузка PNG с прозрачным фоном с помощью SDL3_image
8Observer8 10.02.2026
Содержание блога Библиотека SDL3_image содержит инструменты для расширенной работы с изображениями. Пошагово создадим проект для загрузки изображения формата PNG с альфа-каналом (с прозрачным. . .
Установка Qt-версии Lazarus IDE в Debian Trixie Xfce
volvo 10.02.2026
В общем, достали меня глюки IDE Лазаруса, собранной с использованием набора виджетов Gtk2 (конкретно: если набирать текст в редакторе и вызвать подсказку через Ctrl+Space, то после закрытия окошка. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru