-
Notifications
You must be signed in to change notification settings - Fork 1.4k
java的vector类为什么被认为过时了 #43
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
21 changes: 21 additions & 0 deletions
contents/why-is-java-vector-class-considered-obsolete-or-deprecated.md
This file contains hidden or 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
## 为什么Java的```Vector```类被认为是过时的或者废弃的 | ||
### 问题 | ||
为什么java ```Vector```类被认为是一个遗留的,过时的或废弃的类?在并发操作时,使用它是无效的吗? | ||
|
||
如果我不想手动对对象实现同步,只想用一个线程安全的集合而无需创建底层数组的全新副本(如```CopyOnWriteArrayList```一样)。这种情况下,我使用```Vector```合理吗? | ||
|
||
然后就是关于栈的问题,它是Vector的一个子类,我应该用什么代替它? | ||
### 回答 | ||
Vector中对每一个独立操作都实现了同步,这通常不是我们想要的做法。对单一操作实现同步通常不是线程安全的(举个例子,比如你想遍历一个Vector实例。你仍然需要申明一个锁来防止其他线程在同一时刻修改这个Vector实例。如果不添加锁的话 | ||
|
||
通常会在遍历实例的这个线程中导致一个``` ConcurrentModificationException ```)同时这个操作也是十分慢的(在创建了一个锁就已经足够的前提下,为什么还需要重复的创建锁) | ||
|
||
当然,即使你不需要同步,Vector也是有锁的资源开销的。 | ||
|
||
总的来说,在大多数情况下,这种同步方法是存在很大缺陷的。正如Mr Brain Henk指出,你可以通过调用```Collections.synchronizedList```来装饰一个集合 -事实上 ```Vector``` 将"可变数组"的集合实现与"同步每一个方法"结合起来的做法是另一个糟糕的设计; | ||
|
||
各个装饰方法能够更明确的指示其关注的功能实现。 | ||
|
||
对于```Stack```这个类-我更乐于使用```Deque/ArrayDeque```来实现 | ||
|
||
stackoverflow讨论地址: http://stackoverflow.com/questions/1386275/why-is-java-vector-class-considered-obsolete-or-deprecated |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.