Skip to content
GitLab
Menu
Projects
Groups
Snippets
Help
Projects
Groups
Snippets
Loading...
Help
Help
Support
Community forum
Keyboard shortcuts
?
Submit feedback
Sign in
Toggle navigation
Menu
Open sidebar
cs2-22wi
lectures
Commits
c3826ab8
Commit
c3826ab8
authored
3 years ago
by
Adam Blank
Browse files
Options
Download
Email Patches
Plain Diff
Add new file
parent
dda4bfa0
master
No related merge requests found
Changes
1
Hide whitespace changes
Inline
Side-by-side
Showing
1 changed file
04/OurArrayIntList.java
+87
-0
04/OurArrayIntList.java
with
87 additions
and
0 deletions
+87
-0
04/OurArrayIntList.java
0 → 100644
View file @
c3826ab8
public
class
OurArrayList
<
E
>
implements
IList
<
E
>
{
private
E
[]
data
;
private
int
size
;
public
OurArrayList
(
int
initialCapacity
)
{
this
.
data
=
(
E
[])
new
Object
[
initialCapacity
];
this
.
size
=
0
;
}
public
OurArrayList
()
{
this
(
10
);
}
public
String
toString
()
{
if
(
this
.
size
==
0
)
{
return
"[]"
;
}
String
result
=
"["
;
for
(
int
i
=
0
;
i
<
this
.
size
;
i
++)
{
result
+=
this
.
data
[
i
]
+
", "
;
}
result
=
result
.
substring
(
0
,
result
.
length
()
-
2
);
return
result
+
"]"
;
}
public
void
add
(
E
element
)
{
this
.
add
(
this
.
size
,
element
);
}
/**
* Puts element at index idx, shifting over everything after to the right.
* @param idx
* @param element
* For example, idx = 2, element = 42
* [1, 2, 3, 4, 5]
* ^
* [1, 2, 42, 3, 4, 5]
*/
public
void
add
(
int
idx
,
E
element
)
{
resize
();
for
(
int
i
=
this
.
size
;
i
>
idx
;
i
--)
{
this
.
data
[
i
]
=
this
.
data
[
i
-
1
];
}
this
.
data
[
idx
]
=
element
;
this
.
size
++;
}
private
void
resize
()
{
// size vs. capacity < how much storage space in the list
// ^ how many elements in the list
// capacity == this.data.length
if
(
this
.
size
==
this
.
data
.
length
)
{
// Time to resize!
E
[]
newData
=
(
E
[])
new
Object
[
this
.
data
.
length
*
2
];
for
(
int
i
=
0
;
i
<
this
.
size
;
i
++)
{
newData
[
i
]
=
this
.
data
[
i
];
}
this
.
data
=
newData
;
}
}
@Override
public
int
size
()
{
return
this
.
size
;
}
@Override
public
void
set
(
int
idx
,
E
elem
)
{
if
(
idx
<
0
||
idx
>=
this
.
size
)
{
throw
new
IllegalArgumentException
(
idx
+
" is not a valid index!"
);
}
this
.
data
[
idx
]
=
elem
;
}
public
E
get
(
int
idx
)
{
if
(
idx
<
0
||
idx
>=
this
.
size
)
{
throw
new
IllegalArgumentException
(
idx
+
" is not a valid index!"
);
}
return
this
.
data
[
idx
];
}
@Override
public
void
clear
()
{
this
.
size
=
0
;
}
}
This diff is collapsed.
Click to expand it.
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
.
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment
Menu
Projects
Groups
Snippets
Help