小编Nik*_*sov的帖子

如何在javadoc中使用@value标签?

我正在使用一个私有构造函数而不是枚举的类(这是一个要求).现在我正在尝试添加javadoc标记来记录每个public static final实体.

1)放置javadoc标签的首选位置:喜欢ob1还是ob2

2)两个选项都会在IDEA中产生错误 @value tag must reference field with a constant intializer.

/**
 * {@value #ob1} object1 description
 */

public class MyClass {
    public static final Object ob1 = new Object();

    /**
     * {@value #ob2} object2 description
     */ 
    public static final Object ob2 = new Object();

    private MyClass() {}   
}
Run Code Online (Sandbox Code Playgroud)

java documentation javadoc intellij-idea

37
推荐指数
2
解决办法
3万
查看次数

Java:JPanel中的垂直对齐

我试图在一个JPanel中垂直对齐(居中)两个JLabel.

JPanel panel = new JPanel();
panel.setPreferredSize(size);
JLabel label1 = new JLabel(icon);
JLabel label2 = new JLabel("text");
panel.add(label1);
panel.add(label2);
Run Code Online (Sandbox Code Playgroud)

我尝试过使用setAligmentY()但没有成功.两个标签始终显示在JPanel的顶部.

UPD:标签应该像使用FlowLayout一样位于彼此旁边,但是在JPanel的中间.

java swing jlabel alignment jpanel

17
推荐指数
2
解决办法
6万
查看次数

String.replace实现真的很有效吗?

我以前认为String.replace比String.replaceAll更快,因为后者使用Pattern正则表达式而前者不使用.但事实上,在性能或实施方面没有显着差异.就是这个:

public String replace(CharSequence target, CharSequence replacement) {
    return Pattern.compile(target.toString(), Pattern.LITERAL).matcher(
        this).replaceAll(Matcher.quoteReplacement(replacement.toString()));
}
Run Code Online (Sandbox Code Playgroud)

这里有什么需要使用Pattern?我写了一个非正则表达式替换版本

static String replace(String s, String target, String replacement) {
    StringBuilder sb = new StringBuilder(s);
    for (int i = 0; (i = sb.indexOf(target, i)) != -1; i += replacement.length()) {
        sb.replace(i, i + target.length(), replacement);
    }
    return sb.toString();
}
Run Code Online (Sandbox Code Playgroud)

并比较了表现

    public static void main(String args[]) throws Exception {
        String s1 = "11112233211";
        for (;;) {
            long t0 = System.currentTimeMillis();
            for (int i = 0; i < 1000000; …
Run Code Online (Sandbox Code Playgroud)

java

13
推荐指数
1
解决办法
3444
查看次数

所有自然数总和N,反转总和为1

我有一个问题要解决.N给出了自然数.我需要找到一个自然数列表,它总结了给定的数字,同时反转最多为1.

a + b + c + ... = N
1/a + 1/b + 1/c + ... = 1
Run Code Online (Sandbox Code Playgroud)

a,b,c不必是唯一的.

我在Java中提出了以下代码.它适用于简单的情况,但已经非常缓慢N > 1000.

如何重写方法,以便即使对数百万人也能快速工作?也许,我应该放弃递归或用数学技巧切断一些分支,我想念?

SSCEE:

private final static double ONE = 1.00000001;

public List<Integer> search (int number) {
    int bound = (int)Math.sqrt(number) + 1;
    List<Integer> list = new ArrayList<Integer>(bound);

    if (number == 1) {
        list.add(1);
        return list;
    }

    for (int i = 2; i <= bound; i++) {
        list.clear();
        if …
Run Code Online (Sandbox Code Playgroud)

java algorithm optimization recursion numbers

10
推荐指数
1
解决办法
1957
查看次数

ElasticSearch 中索引关闭的用例是什么?

我发现 ES 索引可以关闭。 https://www.elastic.co/guide/en/elasticsearch/reference/6.3/indices-open-close.html

封闭索引在集群上几乎没有开销(除了维护其元数据),并且被阻止进行读/写操作。

我正在尝试优化 ES 以写入大量数据,即每秒 10 万条消息。每小时都会创建新索引,并且不再使用旧索引进行写入。但是,可以从较旧的索引中读取。

如果我需要对它们执行搜索,我是否应该关闭旧索引以优化写入并按需打开它们?

lucene indexing elasticsearch

9
推荐指数
1
解决办法
7694
查看次数

java程序启动时会发生什么?

最近已经触及Java类加载器并突然认识到,当有人调用时,不能完全理解一步一步发生的事情

java -jar App.jar
Run Code Online (Sandbox Code Playgroud)

好吧,我想

  1. 创建了一个新的JVM实例
  2. 它使用ClassLoader加载主类和其他类
  3. 字节码开始从main()方法执行

但我仍然认为有很多事情我需要了解更多.

  • 谁和如何决定在启动时应该加载哪些类以及哪些类曾经需要?

我找到了两个相关的问题,但没有解释如何将其应用于Java现实.

计算机程序运行时会发生什么?

运行程序会发生什么?

java jvm jar executable-jar classloader

8
推荐指数
1
解决办法
4448
查看次数

Process.exitValue()和Process.destroy()功能

我一直在尝试ProcessProcessBuilder并配备了这种SSCCE.

        import java.io.IOException;
        public class TestProcess {
            public static void main(String[] args) {
                Process process = null;
                ProcessBuilder pb = new ProcessBuilder("notepad.exe");

                try {
                    process = pb.start();
                } catch (IOException e) {e.printStackTrace();}

                //have some time to close notepad
                try {
                    Thread.sleep(10*1000);
                } catch (InterruptedException ignored) {}

                try {
                    System.out.println(process.exitValue());
                 } catch (IllegalThreadStateException e) {
                    System.out.println(e);
                 }

                 if (process != null)
                     process.destroy();

                 /*try {
                     Thread.sleep(0, 1);
                 } catch (InterruptedException ignored) {}*/

                 System.out.println(process.exitValue());
             }
         }
Run Code Online (Sandbox Code Playgroud)
  1. 如果我在10秒超时之前运行此代码并关闭记事本.destroy()在尝试停止已经终止的进程时,调用没有显示任何问题. …

java windows process processbuilder

8
推荐指数
1
解决办法
2万
查看次数

ScheduledExecutorService一个线程很多任务

我是新手,ExecutorService并想知道为什么下面的代码正确打印"10 15",即使我只创建了一个线程来处理超时?为什么我可以多次调用调度而不在单个线程执行器上取消先前的任务?

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;


public class TestExecutorService implements Runnable {
    public static ScheduledExecutorService SERVICE = Executors.newSingleThreadScheduledExecutor();
    private int delay;


    public TestExecutorService(int delay) {
        this.delay = delay;
    }

    public void run () {
        System.out.println(delay);
    }

    public static void main (String[] args) {
        SERVICE.schedule(new TestExecutorService(10), 10, TimeUnit.SECONDS);
        SERVICE.schedule(new TestExecutorService(15), 15, TimeUnit.SECONDS);

        SERVICE.shutdown();
    }
}
Run Code Online (Sandbox Code Playgroud)

java multithreading timer executorservice scheduledexecutorservice

7
推荐指数
2
解决办法
2万
查看次数

JLabel ToolTip会干扰MouseListener

我有Java Swing应用程序 ToolTipMouseTest

关键路线是label.setToolTipText("label" + i);.一旦被注释掉,2 mousePressed在控制台中点击一个标签即可生成.启用此行后,单击标签将不会产生任何效果.

这是预期的行为还是一个错误?我的目标是在不禁用MouseListener工作的情况下显示工具提示.

几乎是SSCCE,但没有进口:

public class ToolTipMouseTest {

public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            new ToolTipMouseTest();
        }
    });
}

public ToolTipMouseTest() {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLayout(new BorderLayout());

    JLayeredPane lpane = new JLayeredPane() {
        @Override
        public Dimension getPreferredSize() {
            return new Dimension(600,400);
        }
    };

    MouseAdapter1 mouseAdapter1 = new MouseAdapter1();
    lpane.addMouseListener(mouseAdapter1);

    frame.add(lpane);

    JPanel panel1 = new JPanel();
    panel1.setSize(new Dimension(600, …
Run Code Online (Sandbox Code Playgroud)

java swing jlabel tooltip mouselistener

6
推荐指数
1
解决办法
1904
查看次数

Spring TransactionSystemException 中的 Hibernate 验证结果

我正在使用 Spring 4.3.3、Spring Data 1.10.5、Hibernate 5.0.11 和 Hibernate Validator 5.3.1。

问题是当验证失败时我期望

org.hibernate.exception.ConstraintViolationException
Run Code Online (Sandbox Code Playgroud)

被排除在我的 JUnit 测试之外,而是

org.hibernate.cfg.beanvalidation.BeanValidationEventListener.validate(BeanValidationEventListener.java:138)
Run Code Online (Sandbox Code Playgroud)

投掷

javax.validation.ConstraintViolationException
Run Code Online (Sandbox Code Playgroud)

这最终导致奇怪的结果

org.springframework.transaction.TransactionSystemException
Run Code Online (Sandbox Code Playgroud)

我该如何修复它?

代码可在GitHub上找到,第 24 行和第 29 行。

完整的堆栈跟踪是

org.springframework.transaction.TransactionSystemException: Could not commit JPA transaction; nested exception is javax.persistence.RollbackException: Error while committing the transaction

at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:526)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:761)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:730)
at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:484)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:291)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
at com.sun.proxy.$Proxy67.createAccount(Unknown Source)
at com.urlshortener.service.AccountServiceImplTest.testCreateAccountEmptyName(AccountServiceImplTest.java:63)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47) …
Run Code Online (Sandbox Code Playgroud)

java spring hibernate hibernate-validator

6
推荐指数
2
解决办法
2382
查看次数